Question

What is the fastest way to zero out an unsigned int?

I am currently just setting the value to 0, but I don't know if there are any tricks for zeroing out a variable? I need a few clock cycles back in my current project. I am using a standard 8051 processor and I have two different variables I need to get to zero if that helps at all.

Was it helpful?

Solution

The question is labelled 8051, so if the need is to zero out a register XORing the register with itself will be a faster way to zero it out, instead of moving a zero in it. One opcode fetch and decode vs opcode fetch decode and operand fetch.

If you are using higher level language and not hand assembling or writing in asm, then it is better to use var = 0. The compiler will take care of the required optimizations.

OTHER TIPS

Write your code for humans, don't waste any effort optimizing things that don't need to be optimized. When you want to assign zero to variable, then assign zero to variable: x = 0;

It's easier to make a correct program fast than it's to make a fast program correct.

I believe the compiler will optimize this sort of thing for you. Remember that micro-optimizations lead to micro-results.

Micro-optimizations lead to micro-results.

You can likely xor a variable with itself to achieve zero. Chances are great your compiler is already doing it that way, if not something faster.

First try to implement a way of timing a block of code containing the code in question, if you have not already done that.

Then, try var = 0; and use the compiler switch that generates assembler in the listing. Then do the same thing for the XOR solution. It represents a bit of extra work, but then you'll have the results right there.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top