0

This may seem tedious, but I know that in JavaScript it was best practices for optimization to declare a local variable if an object property would be used more than once. For example:

var i, length = array.length;
for(i = 0; i < length; i++) {
  console.log(length);
}

I was curious if in Java whether that would be the same case, such as in this example where I use values.length twice.

for(int i = 0; i < values.length && length < values.length + i; i++) {
  vector[i + index] = values[i];
}
  • It will not affect the performance for sure if you use values.length inline or declare a variable for it. It may however, improve the readability of your program. – S.K. Aug 17 '18 at 05:35
  • 1
    You cannot do that in java, and need not, the property is always present. Besides, these are miniscule things that won't matter, and probably will be changed by the JIT if they do. – Matsemann Aug 17 '18 at 05:35
  • @Matsemann Given this is a question about Java, a question about Javascript is **not** a duplicate. – Mark Rotteveel Aug 18 '18 at 13:31

1 Answers1

1

I would say it depends. In your example it doesn't change anything. Create local variable is as fast as use length property. But it's not very common to use fields from class, instead of this we all use getters, eg:

// not used
class Person {
    public String name;
}

// used
class Person {
    private String name;

    public String getName() {
        return name;
    }
}

In this scenario using getName() is also as fast as local variable, but getName() is a method and inside can be anything. You can have inside very complex calculation (it's not recommended but you cannot forbid this). In this case, local variable should be faster because you calculate only once.

rechandler
  • 756
  • 8
  • 22