I’m currently doing a University project which is marked heavily upon the speed and efficiency of my solution. Minor changes I make to the code have massive impacts, as the particular function I am writing is called many hundreds of thousands of times.
I have written the main functionality of my project now, and am currently in the process of optimising everything I possibly can. One particular part of my code that I am questioning looks like this:
array[i] *= -1;
Which I was considering optimising to:
array[i] = 0 - array[i];
Would changing this code actually affect the speed? Is a subtraction operation faster than a multiplication operation? Or is this kind of issue a thing of the past?
Overlooking the fact that you should probably use this instead:
as it’s much clearer IMO since it directly states intent, lets check what the compiler does (GCC 4.7.2 on x86-64) for this program:
And for this:
Now compare the two assembly outputs:
Nothing is printed. The compiler generated the same exact code for both versions. So the answer is: it doesn’t matter what you use. The compiler will choose whatever is fastest. This is a pretty easy optimization to make (if you can even call it an optimization), so we can assume that virtually every compiler out there will pick the fastest way to do it for a given CPU architecture.
For reference, the generated code is:
int main() { time_t t = time(NULL); mov edi,0x0 call 12 mov QWORD PTR [rbp-0x8],rax t *= -1; neg QWORD PTR [rbp-0x8] t = 0 - t; neg QWORD PTR [rbp-0x8] return 0; mov eax,0x0 }In both cases, it uses NEG to negate the value.
t *= -1andt = 0 - tboth generate: