Lambda's lazy loading technology

Lambda's lazy loading technology

Ordinary code splicing string

Code example

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

    public static void main(String[] args) {
        String message1="Hello";
        String message2="world";
        String message3="world";
        show(1,message1+message2+message3);
        show(2,message1+message2+message3);
    }
}

problem found:

I found a performance waste problem. When
calling the show method, the second parameter passed is a spliced ​​string.
First splicing the string before proceeding to the show method. In the
show method, if the log level is not 1,
then the splicing will not be returned. After the string, so the string was wasted splicing

Use lambda functional interface to implement string code splicing

Define a functional interface

Advantage:

Use lambda expressions as parameters to pass, just pass the parameters to the show method.
Only when the conditions are met, and the log level is level 1
, the method in the interface show will be called. The
string will be spliced
. If the level is not 1
, the method show in the interface will not be executed,
so the splicing code will not be executed,
so there is no performance waste.

@FunctionalInterface
public interface Demo02Logger {
    String show();
}

Define a class to fulfill the requirements

import java.util.logging.Logger;

public class Demo02LoggerLambda {
    public  static  void show(int i, Demo02Logger logger)
    {
        if (i==1)
            System.out.println(logger.show());
    }
    public static void main(String[] args) {
        String message1="Hello";
        String message2="world";
        String message3="world";
        show(1,()->{return message1+message2+message3;});

        show(2,()->{
            System.out.println("不满足条件不执行!!!");
            return message1+message2+message3;});

    }
}

Guess you like

Origin blog.csdn.net/tangshuai96/article/details/104265606