Using return statement inside java stream

  • A+
Category:Languages

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.

 


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.

Comment

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