Compiler / JIT optimization of checking for loop bounds in Java and C ++

I learned from this answer in loops forand whilein C # that: "The / JIT compiler has optimizations for this scenario, if you use arr.Lengththe condition:"

for(int i = 0 ; i < arr.Length ; i++) {
    Console.WriteLine(arr[i]); // skips bounds check
}

This made me wonder if the java compiler has such an optimization.

for(int i=0; i<arr.length; i++) {
    System.out.println(arr[i]); // is bounds check skipped here?
}

I think the way it is? The same thing happens when used Collectionlike ArrayList?


But what if I need to use a value myList.size()inside the body of a for loop, now counting myListas an ArrayList? So in this case help will not myList.size()help, since size()is a method call? For example, there might 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: java, .

Q: ++ (++ 98/++ 11) , . vector.size() string.size()? , ?

for (int i = 0; i < myvector.size(); ++i)
    cout << myvector[i] << " "; // is bounds checking skipped here, like in C#?

// 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] << " ";

, std::string?

+4
1

Java

Java 7, , , . Java 7 JIT AOT . JIT AOT for (int i = 0; i < arr.length; i++), , for (int i = 0; i < 10000000; i++), . , , .

, , . , -, JIT AOT , ( , , , Java , , ), , .

++

++ operator []. at. at , , , , , , . , , , , .

++ , Dead Code Elimination, int size for. , , . ( size : for (int i = 0, size = myvector.size(); i < size; ++i))

+2

Source: https://habr.com/ru/post/1628677/


All Articles