Most Efficient way to set Register to 1 or (-1)

Bob picture Bob · May 13, 2010 · Viewed 12.3k times · Source

I am taking an assembly course now, and the guy who checks our home assignments is a very pedantic old-school optimization freak. For example he deducts 10% if he sees:

mov ax, 0

instead of:

xor ax,ax

even if it's only used once.

I am not a complete beginner in assembly programing but I'm not an optimization expert, so I need your help in something (might be a very stupid question but I'll ask anyway): if I need to set a register value to 1 or (-1) is it better to use:

mov ax, 1

or do something like:

xor ax,ax
inc ax

I really need a good grade, so I'm trying to get it as optimized as possible. ( I need to optimize both time and code size)

Answer

paxdiablo picture paxdiablo · May 13, 2010

A quick google for 8086 instructions timings size turned up http://8086.tk/ which seems to have all the timings and sizes for the 8086 (and more) instruction sets.

No doubt you could find official Intel doco on the web with similar information.

For your specific question:

xor ax,ax
inc ax

takes 3+3=6 clock cycles and 2+1=3 bytes while

mov ax,1

takes 4 clock cycles and 3 bytes.

So the latter is better in that case.


But you need to talk to your educational institute about this guy. 10% for a simple thing like that beggars belief.

You should ask what should be done in the case where you have two possibilities, one faster and one shorter.

Then, once they've admitted that there are different ways to code depending on what you're trying to achieve, tell them that what you're trying to achieve is readability and maintainability and seriously couldn't give a flying leap about a wasted cycle or byte here or there*a.

Optimisation is something you generally do if and when you have a performance problem, after a piece of code is in a near-complete state - it's almost always wasted effort when the code is still subject to a not-insignificant likelihood of change.

For what it's worth, sub ax,ax appears to be on par with xor ax,ax in terms of clock cycles and bytes, so maybe you could throw that into the mix next time to cause him some more work.

*a) No, don't really, but it's fun to vent occasionally :-)