In terms of number of operations, compiling time and good practices, is there any difference by doing
for(int i = 0; i < x.size(); i )
instead of
int size = x.size();
for(int i = 0; i < size; i )
If there were no compiling optimization I'd say the latter would be preferable, because it is not calling the function stack every time, it assigns one time a variable and then accesses it instead of calling a function.
Does compiling optimization handle this underneath? Let's say I wanted to optimize the code to the most computationally economic as possible; would it be any different?
CodePudding user response:
Does compiling optimization handle this underneath?
Depends. If the loop content is simple enough, then it may handle it. Otherwise, probably not.
Note that if the loop body changes the size, then the loops are not interchangeable.
CodePudding user response:
Does compiling optimization handle this underneath? Let's say I wanted to optimize the code to the most computationally economic as possible; would it be any different?
Usually, yes. Compiler optimizations handle the best method.
In your case, clang 13.1.6 produces identical code. I created a size1.cpp
with your one line for() and a size2.cpp
for the two line example.
% cc -O3 -std=c 20 -o size1 size1.cpp -lc ; ./size1 ; cc -O3 -std=c 20 -S size1.cpp ; ls -l size1.s ; cc -O3 -std=c 20 -o size2 size2.cpp -lc ; ./size2 ; cc -O3 -std=c 20 -S size2.cpp ; ls -l size2.s ; diff size1.s size2.s
size1 180
-rw-r--r-- 1 risner staff 13298 Sep 15 07:55 size1.s
size2 180
-rw-r--r-- 1 risner staff 13298 Sep 15 07:55 size2.s
435c435
< .asciz "size1 "
---
> .asciz "size2 "
Here are the files:
// size1.cpp
#include <iostream>
#include <array>
int main() {
int a[8] = { 5, 10, 15, 20, 25, 30, 35, 40 };;
std::array<int, 8> x = std::to_array(a);
int z = 0;
for(int i = 0; i < x.size(); i )
z = x[i];
std::cout<< "size1 " << z << "\n";
}
// size2.cpp
#include <iostream>
#include <array>
int main() {
int a[8] = { 5, 10, 15, 20, 25, 30, 35, 40 };;
std::array<int, 8> x = std::to_array(a);
int z = 0, size = x.size();
for(int i = 0; i < size; i )
z = x[i];;
std::cout<< "size2 " <<z << "\n";
}