问题
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