Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Downsides of using Java var keyword

Tags:

java

jvm

bytecode

A presenter just cited that changing to var is useful syntactic-sugar (aligning variable names). I thought I'd check and found...

    List<String> list = new ArrayList<>(); // IMO this is safer future-proof coding
    list.add("HELLO WORLD");

... generates bytecode with an invokeinterface dispatch ...

 11: invokeinterface #12,  2           // InterfaceMethod java/util/List.add:(Ljava/lang/Object;)Z

Converting to Java 10+ var ...

    var list = new ArrayList<>();
    list.add("HELLO WORLD");

... generates bytecode with an invokevirtual dispatch ...

 11: invokevirtual #12                 // Method java/util/ArrayList.add:(Ljava/lang/Object;)Z

Should I be concerned with, say, bulk upgrading a whole application's sourcecode with var? E.g. Will sensitive sections be slower (or faster?! given invokeinterface involves more steps?) Aside from that, are there other non-technical impacts (I saw an interesting comment about the clarity of offline code review for example)

like image 499
drekbour Avatar asked Oct 22 '25 07:10

drekbour


1 Answers

The reason the bytecode differs is because the var declaration infers the type ArrayList rather than List. It's equivalent to you writing ArrayList<String> list = new ArrayList<>(); explicitly. So if you wouldn't worry about changing List to ArrayList in your variable declaration, you shouldn't worry about changing it to var either.

like image 163
Antimony Avatar answered Oct 23 '25 20:10

Antimony



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!