当不涉及集合时,Java 8 Lambdas如何与普通方法调用进行比较?

时间:2014-05-08 18:56:47

标签: java performance lambda

在Java 8中,选择使用功能接口而不是vanilla方法调用会对性能产生什么影响?

假设我必须多次调用一个方法,使用5个参数中的3个重复值:

boolean isGood = getIsGood();
boolean isOk = getIsOk();
int year = getYear();

processCitiesByYear("Germany", "Berlin", isGood, isOk, year);
processCitiesByYear("USA", "New York City", isGood, isOk, year);
processCitiesByYear("Italy", "Rome", isGood, isOk, year);
processCitiesByYear("Japan","Tokyo", isGood, isOk, year);
processCitiesByYear("Canada","Montreal", isGood, isOk, year);
processCitiesByYear("Spain","Madrid", isGood, isOk, year);

我可以创建java.util.function.BiConsumer以避免“isGood, isOk, year”重复,并使代码更具可读性(imho):

boolean isGood = getIsGood();
boolean isOk = getIsOk();
int year = getYear();

BiConsumer<String, String> processGoodAndOkInYear= 
    (country, city) -> {
        processCitiesByYear(country, city, isGood, isOk, year);
    };

processGoodAndOkInYear.accept("Germany", "Berlin");
processGoodAndOkInYear.accept("USA", "New York City");
processGoodAndOkInYear.accept("Italy", "Rome");
processGoodAndOkInYear.accept("Japan","Tokyo");
processGoodAndOkInYear.accept("Canada","Montreal");
processGoodAndOkInYear.accept("Spain","Madrid");

我是否因为这种“设计模式”而牺牲了性能?或者JVM是否神奇地turns my processGoodAndOkInYear into compiled code并且它实际上比5个参数调用更有效?

1 个答案:

答案 0 :(得分:0)

好吧,我不认为Lambda可能比方法调用更快,但它应该非常接近。您可以查看以下链接:

现在,我不会在这里使用Lambda,因为一个简单的包装器方法会:

private void processGoodAndOkin2001(String country, String city) {
    processCitiesByYear(country, city, true, true, 2001);
}

Perfs将采用这种方式。