mirogula
6/12/2017 - 6:20 PM

Anonymous class vs. Lambda

Anonymous class vs. Lambda

import java.util.ArrayList;
import java.util.List;

public class Main {

    public static void testRun(Runnable r) {
        r.run();
    }

    public static void main(String[] args) {
        List<Long> partialResults = new ArrayList<>();
        for(int i=0; i<20; i++) {
            long start = System.currentTimeMillis();
            for (int j = 0; j < (int) 10e9; j++) {

                // -- lambda
//                testRun(() -> {
//                    int x = 1 + 1;
//                });
                // --

                // -- anon class
                testRun(new Runnable() {
                    @Override
                    public void run() {
                        int x = 1 + 1;
                    }
                });
                // --
            }
            long stop = System.currentTimeMillis();
            partialResults.add(stop-start);
        }
        partialResults.stream().
                peek(time -> System.out.println(time+" ms")).
                reduce((t1, t2) -> t1+t2).
                ifPresent(sum -> System.out.println("avg time: "+sum/partialResults.size()+" ms"));
    }
}