0

Is it better coding practice to pre-compute and save the length of an array before looping through the object? Similarly, what about for strings?

//Given int Array A, that won't change size
for (int i = 0; i < A.length; i++)
     System.out.println(A[i]);

vs

int Asize = A.length;
for (int i = 0; i < Asize; i++)
    System.out.println(A[i]);

-- similarly for strings

//Given string s, that won't change size
for (int i = 0; i < s.length(); i++)
    System.out.println(s.charAt(i));

vs

//Given string s, that won't change size
int sSize = s.length();
for (int i = 0; i < sSize; i++)
    System.out.println(s.charAt(i));
RGRGRG
  • 3
  • 1
  • The difference, if any, is vanishingly small. – Andy Turner Feb 16 '18 at 19:29
  • Thanks. Is the same true for strings? – RGRGRG Feb 16 '18 at 19:36
  • 1
    The following is always true: *Don't worry about performance, worry about writing readable code. That doesn't mean to write wildly inefficient code; but don't worry about minutiae. When you find code is too slow, profile it; only when you find that this is the most important bottleneck in your code should you try alternatives.* – Andy Turner Feb 16 '18 at 19:40

0 Answers0