Search code examples
javaarraysoptimization

Is there any advantage to int i = array.length over just calling array.length twice?


Is any benefit--small as it may be--of putting the length of an array into an int in this situation, or is simply calling array.length twice better? Or does compiler optimization make these approaches equivalent?

No int:

Vector<String> vs = new Vector<String>(a_o.length);
for(int i = 0; i < a_o.length; i++)  {
   vs.add(a_o[i]);
}

int:

int iLen = a_o.length;
Vector<String> vs = new Vector<String>(iLen);
for(int i = 0; i < iLen; i++)  {
   vs.add(a_o[i]);
}

Solution

  • The compiler is smart, trust it. It'll optimize it.

    Don't waste time on performance issues like this one, worry more about other things like data structures..