0

I am trying to find what speciality of lambda makes it different from conventional method. To find time consumption between lambda expression and Anonymous class, i have created a sample code and found that the time consumption of lambda is too high. Am i correct?

public class Test {
    public static void main(String[] args) {

        long str = System.nanoTime();
        usingLambda();
        long end = System.nanoTime();
        System.out.println("Differnce: usingLambda: " + (end - str) + "ns");

        long str2 = System.nanoTime();
        usingAnonymousClass();
        long end2 = System.nanoTime();
        System.out.println("Differnce usingAnonymousClass: " + (end2 - str2) + "ns");

    }

    private static void usingLambda() {
        Messagable lambda = () -> {
            System.out.println("Test.callByLambda()");
        };
        lambda.sendMessage();
    }

    private static void usingAnonymousClass() {
        Messagable anonymous = new Messagable() {
            @Override
            public void sendMessage() {
                System.out.println("Test.usingAnonymousClass()");
            }
        };
        anonymous.sendMessage();
    }
}

interface Messagable {
    public void sendMessage();
}

Output: ParallelArraySorting.callByLambda()
Difference: usingLambda: 46650876ns
ParallelArraySorting.usingAnonymousClass()
Difference usingAnonymousClass: 447249ns

Atishay
  • 41
  • 9
  • 2
    (1) you are not measuring what you think: the `println` takes ***a lot*** more time than the difference between lambda and anonymous class and (2) even then, your benchmark suffers from many flaws. See https://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java – assylias Mar 07 '18 at 12:01
  • 1
    And the results clearly don't correspond to the code you have shown! – assylias Mar 07 '18 at 12:05
  • Thank you, i got it by this reference link : [http://www.oracle.com/technetwork/java/jvmls2013kuksen-2014088.pdf] – Atishay Mar 07 '18 at 12:25

0 Answers0