使用Java的var关键字的缺点

huangapple go评论71阅读模式
英文:

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&lt;String&gt; list = new ArrayList&lt;&gt;(); // IMO this is safer future-proof coding
    list.add(&quot;HELLO WORLD&quot;);

... 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&lt;&gt;();
    list.add(&quot;HELLO WORLD&quot;);

... 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&lt;String&gt; list = new ArrayList&lt;&gt;(); 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 使用Java的var关键字的缺点 所以,如果我是你,我不会担心。唯一可能发生的事情是它可能无法编译,然后你需要将 'var' 回退为有类型的变量。

'var' 创建的唯一问题就是在代码审查时可能会让人头疼。

依我个人看法,至少这样。

英文:

This is java, not PHP 使用Java的var关键字的缺点 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.

huangapple
  • 本文由 发表于 2020年9月4日 05:43:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/63732044.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定