Java Tuple2 difference between using accessor method and calling the variable directly

坚强是说给别人听的谎言 提交于 2019-12-10 06:47:08

问题


I'm using Tuple2 in my Java code, and I was wondering if there was a difference between accessing the values via the getter or just getting the variables directly.

Tuple2<String,String> tuple = new Tuple2<>("Hello", "World");
//getting values directly
String direct = tuple._1;
//using getter
String indirect = tuple._1();

回答1:


The first loads a field where the second invokes the method using getField and invokeVirtual opcodes relatively. The generated byte-code looks like

  13: getfield      #6                  // Field scala/Tuple2._1:Ljava/lang/Object;
  16: checkcast     #7                  // class java/lang/String
  19: astore_2
  20: aload_1
  21: invokevirtual #8                  // Method scala/Tuple2._1:()Ljava/lang/Object;
  24: checkcast     #7                  // class java/lang/String

And the difference is the difference between a field read and a method invocation, ie the JIT compiler is happy to inline the method and it wouldn't matter much performance wise.



来源:https://stackoverflow.com/questions/38729097/java-tuple2-difference-between-using-accessor-method-and-calling-the-variable-di

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!