英文:
Downsides of using Java var keyword
问题
一个演讲者刚刚引用了将代码更改为var的好处,称其为有用的语法糖(使变量名对齐)。我想我会检查一下,然后发现...
    List<String> list = new ArrayList<>(); // 在我看来,这是更安全、面向未来的编码方式
    list.add("HELLO WORLD");
... 生成了一个带有 invokeinterface 分派的字节码 ...
 11: invokeinterface #12,  2           // InterfaceMethod java/util/List.add:(Ljava/lang/Object;)Z
转换为 Java 10+ 的 var ...
    var list = new ArrayList<>();
    list.add("HELLO WORLD");
... 生成了一个带有 invokevirtual 分派的字节码 ...
 11: invokevirtual #12                 // Method java/util/ArrayList.add:(Ljava/lang/Object;)Z
我应该担心一次性将整个应用程序的源代码批量升级为 var 吗?例如,敏感部分会变慢吗(或者更快?鉴于 invokeinterface 涉及更多步骤?)除此之外,还有其他非技术影响吗(我看到有人对离线代码审查的清晰度提出了有趣的评论)。
英文:
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)
答案1
得分: 9
字节码不同的原因是因为var声明推断出类型是ArrayList,而不是List。这相当于您显式编写ArrayList<String> list = new ArrayList<>();。因此,如果您不担心在变量声明中将List更改为ArrayList,那么将其更改为var也不应该成为问题。
英文:
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.
答案2
得分: 0
这是Java,不是PHP 
 所以,如果我是你,我不会担心。唯一可能发生的事情是它可能无法编译,然后你需要将 'var' 回退为有类型的变量。
'var' 创建的唯一问题就是在代码审查时可能会让人头疼。
依我个人看法,至少这样。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论