Search code examples
javac#performanceincrementjit

Is using an int and then incrementing it slower than doing both simultaneously?


I ran into some old source code recently, and I noticed a pattern like this:

T item = array[index];
index++;

Would it be faster to express it as

T item = array[index++];

? Up until recently I thought there wouldn't be a difference, since I thought it was shorthand for index = index + 1, so either way you would be dereferencing index twice. But this post has made me think otherwise; instead, you would only be getting the value of index once.

Would this yield any difference (however small) in performance, or do modern JITs optimize this away?


Solution

  • Most moderns langages will optimise during compile or execute time. Simple things like this will be directly optimised during compilation.

    But note your exemple is just a typo question, in the 2 cases Java will understand T item = array[index++]; by :

    • Get the object in the index place
    • Add 1 to index

    That's the same thing that writting

    T item = array[index];
    index++;
    

    (but not the same thing that T item = array[++index]; that is equivalent to :

    index++;
    T item = array[index];
    

    Edit: I can also add that's the loops are improved too, compile or execute time For exemple in C or C++

    for(int i = 0; i < 1000; i++) {
        t[i] = 0
    }
    

    will become the equivalent to

    for(int i = 0; i < 1000; i++) {
       *(t++) = 0
    }
    

    To conclude, compiler and virtual machine will improve your code, think more about algorithms and data structures chosen.