翻车!居然在这里翻车了!!!

时间:2022-07-26
本文章向大家介绍翻车!居然在这里翻车了!!!,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

首先看代码一:

@FunctionalInterface
public interface MyFunctionInterface {
    public abstract String myMethod();
}
public class Demo {
    private static void show(int i, MyFunctionInterface myFunctionInterface) {
        if (i == 1) {
            System.out.println(myFunctionInterface.myMethod());
        }
    }

    public static void main(String[] args) {
        String msgA = "你好";
        String msgB = "Hello";
        String msgC = "Java";

        show(2, () -> {
            System.out.println("我执行了");
            return msgA + msgB + msgC;
        });
    }
}

再来看代码二:

public class Demo {
    private static void show(int i, String str) {
        if (i == 1) {
            System.out.println(str);
        }
    }

    public static void main(String[] args) {
        String msgA = "你好";
        String msgB = "Hello";
        String msgC = "Java";

        show(2,  msgA + msgB + msgC);
    }
}

此前,我一直认为代码一应该比代码二更省时,毕竟 Lambda 表达式延迟执行,不用提前拼接字符串没有造成性能浪费。然而我在最近重新写 Java 基础博文的时候运行了上述代码,结果 翻车了!

再来看看 idea 运行结果:

代码一执行耗时:34149500 纳秒,代码二执行耗时:28200 纳秒,使用了 Lambda 表达式的代码居然跑不过没有使用的,而且二者完全不是一个数量级。是我对 Lambda 表达式延迟执行有什么误解?还是说 idea 2020.1 对于字符串进行了什么骚操作?