How would you rewrite this python code efficiently in Assembly [closed]

Performance is accomplished via algorithms that do less work or spread the load, and sometimes by special features of assembly or some other language.

Still, here you are doing a lot of searching, with nested for loops and once with .index inside the inner loop.

With another approach to the algorithm, we can avoid all but the outer loop:

Create a map of input character to output character, so for input of ‘a’ you output ‘x’, for ‘d’ output ‘f’, etc.. for upper case, punctuation, and all others, the output is the same value as the input.

Then the algorithm becomes:

for char in NIZ1
    NIZ2 += map[char]

In assembly, or any language, I would make map an array.

Next, you need to look at the += operation, which does string appending, which can be very inefficient.  So, we would prefer to preallocate the space for NIZ2 in advance outside (and before) the loop, and we can do that since we know we will need the same size as for NIZ1, the input string.

i = 0
for char in NIZ1
    NIZ2[i++] = map[char]             # update 1 char instead of string append

Leave a Comment