Search code examples
arraysperformancefor-loopvariablespseudocode

What is more efficient when using a for loop?


In a lot of for loops that work with arrays I see i < arr.length() as the 2nd statement
Would this:
for(i = 0; i < arr.length(); i++){
//do something
}
be LESS efficient than this:
size = arr.length();
for(i = 0; i < size; i++){
//do something
}?
Or is the difference so small I shouldn't care?
This question only applies to languages that need to use a function in order to find the length of an array/list, unlike java, for example, which is object-oriented and arrays have a length propriety arr.length


Solution

  • The first version can be slower regarding the language, the compiler, its configuration and the loop condition.

    Indeed, in C, C++ and Java for example the function is called at each iteration and thus the resulting program can be slower when optimizations are disabled. Other languages, such as Python, have a different kind of loops which walk through given iterables / ranges (eg. list, generators) and the value is evaluated once. In your case, no performance differences should be seen if optimizations are enabled since the function call arr.length() is usually a constant (in the context of the loop execution) and most compilers are good enough to detect this and to produce a fast equivalent code (you can see a simple example in C++ here). However, please note that interpreters generally do not perform such optimizations.