Reputation: 535
Hi have two implementation some piece of code where I am modifying the strings using Java stream:
final List<String> strings = new ArrayList<>();
strings.add("abc");
strings.add("bca");
strings.add("xyz");
Method 1:
final List<String> modifiedStrings = strings.stream().map(a -> {
String abc;
abc = a.replace("a", "*");
return abc;
}).collect(Collectors.toList());
Method 2:
final List<String> modifiedStrings2 = strings.stream().map(a ->
a.replace("a", "*")).collect(Collectors.toList());
I want to know if there is any performance difference between method one and method two.
Upvotes: 6
Views: 12777
Reputation: 262724
No. This will compile to essentially the same bytecode. The second version is just a more concise way to write it.
Example code:
void foo(List<String> strings) {
strings.stream()
.map(
a -> {
String abc;
abc = a.replace("a", "*");
return abc;
})
.collect(Collectors.toList());
}
void bar(List<String> strings) {
strings.stream().map(a -> a.replace("a", "*")).collect(Collectors.toList());
}
Corresponding lambda bytecode:
private static java.lang.String lambda$bar$1(java.lang.String);
descriptor: (Ljava/lang/String;)Ljava/lang/String;
flags: ACC_PRIVATE, ACC_STATIC, ACC_SYNTHETIC
Code:
stack=3, locals=1, args_size=1
0: aload_0
1: ldc #8 // String a
3: ldc #9 // String *
5: invokevirtual #10 // Method java/lang/String.replace:(Ljava/lang/CharSequence;Ljava/lang/CharSequence;)Ljava/lang/String;
8: areturn
LineNumberTable:
line 18: 0
private static java.lang.String lambda$foo$0(java.lang.String);
descriptor: (Ljava/lang/String;)Ljava/lang/String;
flags: ACC_PRIVATE, ACC_STATIC, ACC_SYNTHETIC
Code:
stack=3, locals=2, args_size=1
0: aload_0
1: ldc #8 // String a
3: ldc #9 // String *
5: invokevirtual #10 // Method java/lang/String.replace:(Ljava/lang/CharSequence;Ljava/lang/CharSequence;)Ljava/lang/String;
8: astore_1
9: aload_1
10: areturn
LineNumberTable:
line 11: 0
line 12: 9
So, the bytecode is not quite the same - there is an extra astore_1
and aload_1
in the foo
case; but this is likely irrelevant, as it can just be optimized away.
Upvotes: 17
Reputation: 4054
When the body of a lambda function is just one single expression the compiler determines the return type and value from this expression.
It is just syntactic sugar.
Upvotes: 1