0

Here are two methods.test1() and test2()

public class MoreStreams {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("Brad", "Kate", "Kim", "Jack",
                "Joe", "Mike", "Susan", "George", "Robert", "Julia", "Parker", "Benson");
        test1(names);
        //test2(names);
    }

    private static void test1(List<String> names) {
        List<String> result = names.stream()
                .map(name -> sub(toUpper(toLower(name))))
                .collect(Collectors.toList());
        System.out.println(result);
    }

    private static void test2(List<String> names) {
        List<String> result = names.stream()
                .map(MoreStreams::toLower)
                .map(MoreStreams::toUpper)
                .map(MoreStreams::sub)
                .collect(Collectors.toList());
        System.out.println(result);
    }

    private static String toUpper(String name) {
        System.out.println("to Upper: " + name);
        return name.toUpperCase();
    }

    private static String toLower(String name) {
        System.out.println("to Lower: " + name);
        return name.toLowerCase();
    }

    private static String sub(String name) {
        System.out.println("to Title: " + name);
        return name.substring(1);
    }
}

The first one uses multiple map(), and the second one aggregates all logic together in one map(), do they take the same time or not, and why ? And what if there are more map()s in the chain? Please help me.

Saber
  • 331
  • 1
  • 14

1 Answers1

0

If that will be called so few times that the jit compiler doesn`t have time to inline and optimize, the multimap would in theory be more expensive, due to the extra stackframes/method calls.

However, your main way to measure will require millions of invocations which will jit-compile and inline a lot these micro methods. They could very well end up be equal in performance.

Here is a pile of JVM args to show more of what's going on during your test. I'll let you net-search what they do.

-verbose:gc
-XX:+PrintGCDateStamps
-XX:+PrintGCDetails
-Xloggc:"./gc.log"
-XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=10 -XX:GCLogFileSize=1M
-XX:+PrintGCApplicationStoppedTime
-XX:+PrintCompilation
-XX:+PrintSafepointStatistics
-XX:PrintSafepointStatisticsCount=1
-XX:+UnlockDiagnosticVMOptions  -XX:+LogCompilation -XX:+PrintInlining

The last trio of optins are generating a log file consumable with "JitWatch", a gui program parsing and browsing all that stuff and telling you about jit events in a more friendly way.

You should design your test without the println of course. Also, and this is VERY important, you should return a value for every test otherwise the JIT will figure you don`t use it and skip all your code! Microbenchmarking is a science now! See How do I write a correct micro-benchmark in Java?

user2023577
  • 1,752
  • 1
  • 12
  • 23