One (more) advantage Lambdas offer is Laziness (thereby improving performance):
Before Lambdas, a log statement looks like this:
logger.trace("Costly Metrics: {}", expensiveCompuatation());
The expensiveCompuatation()
gets invoked regardless of whether trace is enabled or not, wasting CPU cycles.
To avoid such costly invocations, we used to write:
if (logger.isTraceEnabled()) {
logger.trace("Costly Metrics: {}", expensiveCompuatation());
}
Although it meets the needs, now the code looks ugly with more if
statements causing code bloat.
After Lambdas, now the log statement looks crisp and neat (without surrounding if statements) and allows delaying the expensive operation:
logger.trace("Costly Metrics: {}", () -> expensiveCompuatation());
logger.trace("Costly Metrics: {}, {}", () -> expensiveOp1(), () -> expensiveOp2());
logger.trace("Costly Metrics: {}, {}", this::expensiveOp1(), this::expensiveOp2());