4 ms·
> To improve the performance, take the redundant multiplication out of the loop like below: Um, that multiplication is already outside the loop. You said befor
by tomsmeding 10y ago
> To improve the performance, take the redundant multiplication out of the loop like below:
Um, that multiplication is already outside the loop. You said before that one shouldn't trust the optimiser, but it did the right thing here...
EDIT: (After reading the entire thing) The memory aliasing point completely correct and very important (even though you probably want the `b[i] = val` outside the inner loop...); in C, I'd argue that this point needs even more attention if we're micro-optimising already.
The strlen call is only repeated (leading to quadratic behaviour) because the string may be modified in the inner loop. Might be worth mentioning that the calls will be hoisted (i.e. merged to one) if the string is constant and nothing can alias to it.
The "replacing multiplication by additions", the replacing multiplication with a shift and the hoisting I mentioned above are all redundant optimisations for a programmer: compilers will trivially do that already. The first two are instances of "strength reduction" and feature in most compilers' -O1 set.
Conclusion: I do like the first part about the actual trivia, but I think the micro-optimisation part misses the point somewhat.
- danbruc 10y agoThe memory aliasing point completely correct and very important (even though you probably want the `b[i] = val` outside the inner loop...) [...] Do you mean the assignment to b should be or must be outside of the inner loop? I am pretty sure it must be outside of the inner loop in order to make the assembly version correct.
- tomsmeding 10y agoVery true, didn't spot that one. Then the C code is probably a typo, but still incorrect. :P
- adwn 10y ago> Um, that multiplication is already outside the loop. You said before that one shouldn't trust the optimiser, but it did the right thing here... It's even more ironic given that the author wrote right above that part: "Always profile the program’s performance." If they'd actually followed their own advice, they'd have noticed that performance was not improved through this manual "optimization".
- 1maginary 10y ago> The "replacing multiplication by additions", the replacing multiplication with a shift and the hoisting I mentioned above are all redundant optimisations for a programmer There's also the fact that the code could get marginally more annoying to maintain, which is honestly more important nowadays even if you were actually saving a few cycles and the compiler wasn't doing the work for you.