Const var make more optimized loops in -O3 GCC/Clang - #2057
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: ASSERTIVE Plan: Pro Plus Run ID: 📒 Files selected for processing (5)
📝 WalkthroughWalkthroughThe change caches panel, vector, and row sizes before loop execution across multiple UI and action modules. It also marks unchanged local size variables as Poem
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
In short calling a function (especially via PLT — Procedure Linkage Table) is an expensive operation for CPU compared to simply reading from ALU register. It requires preparing arguments, jumping through memory, changing the stack pointer, and returning. If htop panel has, for example, 10lines : for loop A will call Panel_size 1 time Increddible. |
609eb26 to
7727886
Compare
|
The const part is not the main issue here, but the repeated call. Often times doing works just the same and also limits the scope of |
|
I like @BenBE's style better as it limits the scope of the temp variable. @GermanAizek: Did you do some benchmarking (perf) how much the loop optimizations save overall? |
Many thanks @fasterit for making me check the loop, I found such a cool optimization on GCC and Clang compilers with the -O3 optimization flag. Amazing results, it's strange that the compiler itself doesn't optimize for -O3.
Example with
actionUntagAll()function:Opt A my branch (with
const int size):Op B master branch (without
const int size):Why separate const int (option A) faster
In Option A, I saved the size to a constant size before the loop started.
In the assembler, we see that the call
Panel_size@PLToccurs only once before the start of the loop (before the label.L34). The result is stored in the%r12dregister, and a simple and very fast comparison with the register takes place inside the loop itself:cmpl %ebx, %r12d.For each iteration of the loop in Variant A, there is 1 function call.:
Why Option B vanilla code slower
In Option B, the exit condition of the loop is calculated anew at each iteration.
There is a label in the assembly code
.L33(which is a loop condition check) contains:Code snippet
This means that for each iteration of the loop in Option B, there are 2 function calls.: