-
Which is faster?
Which snippet is faster? I'm pretty sure B is, but I'm not sure if the extra var dec is hurting.
Code:
// Snippet A
for(x = 0; x < 1000; x++)
{
buff1[x * 10] = x;
buff2[x * 10] = x;
}
Code:
// Snippet B
for(x = 0; x < 1000; x++)
{
DWORD nx = x * 10;
buff1[nx] = x;
buff2[nx] = x;
}
-
I would think any modern compiler would optimize both to be the same.
-
The second should be faster, but why not just compile your code and see for yourself? Some things to note also are that the optimizer may just generate the most optimal way of doing that either way. Also, one last thing: standard logic applies. Multiplication can be expensive, but even if it weren't, which is faster, doing something once or twice?
-
CSE should make them the same with any decent compiler.
-
And CSE is part of the optimizing functions even in Turbo C and other quite old and limited compilers, so if you haven't got it in your current compiler, you probably should look for a better one.
However, sometimes it's a good idea to add an extra variable simply because it makes it easier to see that the calculation of two expression are the same in different places.
[And by the way, I'd expect the compiler do something like this out of that code:
Code:
for(x = 0, nx = 0; x < 1000; x++, nx += 10)
{
buf1[nx] = x;
buf2[nx] = x;
}
, as multiplying by 10 is much more work than adding two variables.
--
Mats