Reputation: 2860
I have an assignment regarding looping in Assembly. Nothing difficult since it's just the start of the course. I have done what was asked and just wanted to see if what I have done is correct. Also, I would like to know if there is anything that is un-needed or could be removed. (I enjoy seeing different ways to go about things and being able to see what is more efficient).
Evaluate the sum of 2n - 5, where n goes from 1 to 7
This is what I have done:
_num1
DB 0
mov cx, 1 ; set counter to 1
mov eax, 0 ; use eax to keep total
eval:
mov [_num1], cx ; set num1 to cx value
shl [_num1], 1 ; double value of num1
add eax, [_num1] ; add values of 2n to eax
sub eax, 5 ; subtract 5 from eax (total)
inc cx ; increment cx
cmp cx, 7 ; check if equal
jne eval
Should this work properly? If so, are there any ways of improving it? If not, what is wrong with the implementation?
Upvotes: 1
Views: 409
Reputation: 1851
Usually one counts CX down and loops until CX hits zero. There's the LOOP mnemonic which does exactly that in a single op. But these days the two commands "dec cx; jnz" combined are faster than LOOP on most CPUs. Use LOOP only when size-optimizing your code to the last bit.
Instead of using a memory reference (_num1) you could use the DX register, it's unused in your code. Registers are way faster than memory references.
Another often used opimization is using "xor eax,eax" instead of "mov eax,0". The MOV will be slower because it copies 4 bytes (0x00000000) from memory to the register. The XOR will clear the EAX register too, but without accessing any memory. It's also slightly smaller code.
As a personal preference, I'd go with higher-level comments. "increment cx" adds nothing to "inc cx". I prefer comments every couple of lines that are more on a high-level-language-level, like "eax = eax + 2*ecx".
More important is that you reserved only a byte for _num1, but then go on to assign two bytes (CX) to it. This will overwrite a byte of other data. If you want _num1 to hold two bytes, use "DW" instead of "DB". Another problem is that you mix operands and registers of different sizes. If you need 32 bit registers, stick with those. Or you could clear the upper 16 bits of the registers before using them. Or you can use the MOVZX mnemonic, which will clear the upper 16 bits when specifying data.
All in all:
Upvotes: 3