lambda函数式编程思想
lambda优化日志案例
public class Demo { public static void show_log(int i ,String msg){ if (i == 1){ System.out.print(msg); } } public static void main(String[] args) { show_log(2,"hello"); show_log(1,"world"); show_log(1,"java"); } }
从案列中可以看出,不管日志级别 是不是1,但是当输出的时候,msg还是会先进行拼接,拼接后才去输出,这就造成了性能浪费。
lambda优点:延时加载
lambda的适用前提,必须存在函数式接口
@FunctionalInterface public interface DemoLambda { public abstract String show_log(); }
public class Demo02 { public static void main(String[] args) { String msg1 = "hello"; String msg2 = "world"; String msg3 = "java"; showLog(2,()->{ return msg1+msg2+msg3; }); } public static void showLog(int level ,DemoLambda msg){ //定义个亿显示日志的方法,方法参数传递日志的等级和msg接口 if (level == 1){ System.out.println(msg.show_log()); } } }
这样就做到了性能优化;