DEV Community

loading...

Does the `var` keyword affect performance in Java?

baenencalin profile image Calin Baenen ・1 min read

Does using var instead of TypeClassName lower performance?
If not, can I use it as sparingly as I want?

Thanks!
Cheers!

Discussion

pic
Editor guide
Collapse
190245 profile image
Dave

The var keyword is interpreted at compile time, as a result, the bytecode inside the jar/war will already have the correct type of object. No performance loss at runtime.

However, there's a lengthy debate around why you would want to use it. My take: if your object name is too long, such that it hurts readability of your code, and you can't refactor - use it.

I don't buy the argument of "I don't know what class it will be" - if the compiler can work it out, so can you. Not knowing is another sign that you should refractor.

Collapse
cyberhck profile image
Nishchal Gautam

TIL: there's a var keyword in Java which does type inference, last time I was doing java, there wasn't, when did they introduce this?

Collapse
rvictorino profile image
Robin Victorino

Type inference with var keyword has been introduced in Java 10 :)

developer.oracle.com/java/jdk-10-l...
openjdk.java.net/jeps/286