Reputation: 31
For example, if I am using the length of an array to determine how many times the code in the for loop runs, should I initialise the count of the array on top of the for loop so that the program does not keep calculating the length of the string?
Some simple code that prints each element in the array:
Without initialising the size of the array
int myArray[5] = { 1,2,3,4,5 };
for (int iPos = 0; iPos < size(myArray); ++iPos)
cout << myArray[iPos];
initialising the size of the array before the for loop
int myArray[5] = { 1,2,3,4,5 };
int sizeOfArray = size(myArray);
for (int iPos = 0; iPos < sizeOfArray; ++iPos)
cout << myArray[iPos];
Upvotes: 2
Views: 73
Reputation: 31458
for (int iPos = 0; iPos < size(myArray); ++iPos)
will calculate the size of myArray
on each iteration.
This may be important if the size of myArray
can change in the body of the loop. So be careful.
If the size of myArray
cannot change in the loop, then extracting the calculation to before the loop as const int sizeOfArray = size(myArray);
may gain you a tiny bit of performance if the compiler does not realize this itself and hoists the calculation out of the loop on its own.
A simpler way to do it would be to just use a range-for loop, since those are defined to only calculate the size once:
for (const auto& element : myArray)
cout << element;
and then you also don't have to worry about having the sizeOfArray
variable exist in the scope outside the loop.
Upvotes: 5
Reputation: 11178
sizeof operator is a compile time one, so there are no problems since you are using static arrays.
For a dynamic array, calling std::vector::size()
could in theory be executed multiple times, but a good optimizing compiler will cache it as long as you don't modify the vector inside a loop.
Even if it doesn't, size() takes little time to execute (constant complexity).
Upvotes: 2