I have learned from this answer on for
and while
loops in C# that: "The compiler/JIT has optimisations for this scenario as long as you use arr.Length
in the condition:"
for(int i = 0 ; i < arr.Length ; i++) {
Console.WriteLine(arr[i]); // skips bounds check
}
This tempted me to wonder if java compiler has such optimizations.
for(int i=0; i<arr.length; i++) {
System.out.println(arr[i]); // is bounds check skipped here?
}
I think it does, well, does it? Does the same happen when using Collection
like ArrayList
?
But what if I have to use the value of myList.size()
inside the body of the for loop, considering now myList
to be an ArrayList? So in that case will not hoisting myList.size()
help, since size()
is a method call? For example may be something like this:
int len = myList.size(); // hoisting for using inside the loop
for(int i = 0; i < myList.size(); i++) { // not using hoisted value for optimization
System.out.println(myList.get(i));
if(someOtherVariable == len) {
doSomethingElse();
}
}
Edit: Though I haven't obtained an answer for java, I am still adding a second part to this question.
Q: Does C++ (C++98/C++11) have such optimisations, e.g. for vector.size()
and string.size()
? For instance, which is better performance-wise?
for (int i = 0; i < myvector.size(); ++i)
cout << myvector[i] << " "; // is bounds checking skipped here, like in C#?
or
// does this manual optimisation help improve performance, or does it make?
int size = myvector.size();
for (int i = 0; i < size; ++i)
cout << myvector[i] << " ";
That said, does such optimisation exist for std::string
as well?