Downsides of using Java var keyword

Viewed 1424

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)

2 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.

This is java, not PHP :) So, I wouldn't worry if I were you. The only thing that could happen is that it will not compile and you need to 'revert' the var to typed variable.

The only issue var creates is a headache during code review.

IMHO, at least.

Related