0

I am curious if it is faster to call an array's length attribute twice while iterating through it, or to make a new variable.

Example of calling length attribute:

private void addColumns() {

   for( int i = 0; i < puzzleArr.length; i++ ) {

      char[] column = new char[puzzleArr[i].length];

      for( int j = 0; j < puzzleArr[i].length; j++ ) {
         // do something
      }
   }

}

Example of making a new variable:

private void addColumns() {

   for( int i = 0; i < puzzleArr.length; i++ ) {
      int arrayLength = puzzleArr[i].length;

      char[] column = new char[arrayLength];

      for( int j = 0; j < arrayLength; j++ ) {
         // do something
      }
   }

}
LuminousNutria
  • 1,883
  • 2
  • 18
  • 44
  • 1
    Take an example of C language. When you define a record , you add few attributes/field and those can be accesed in constant time. Same way, think of java defining an array as struct with a length field in it. – Khan Saab Feb 14 '19 at 23:04
  • @KhanSaab - that kind of misses the point. Both `array.length` and accessing a variable are `O(1)` ... but that doesn't mean that the constant of proportionality is the same in all cases. See the linked Q&A for a more detailed explanation. – Stephen C Feb 14 '19 at 23:13
  • @StephenC how can one mention the constants with Big-O notation? I see very few people using tilde notation and i prefer that but not everyone knows about that. – Khan Saab Feb 15 '19 at 12:20
  • 1
    My point is that you are ignoring the constants! You say *"can be accessed in constant time"*, but ignore the fact that the constants are different. Even in C, accessing a field of a `struct` and a variable don't necessarily take the same time. – Stephen C Feb 16 '19 at 00:40

0 Answers0