Reputation: 3151
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();
Upvotes: 4
Views: 655
Reputation: 23329
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.
Upvotes: 2