Java 字符串参数化 - 间接 toString 方法的性能损失 [英] Java String Parameterization - Performace loss on indirect toString methods
问题描述
我有一个像这样的 method
:
private String getOrderListAsString() {
StringBuilder str = new StringBuilder();
str.append("Sell list:");
for (Order o : sellOrderList) {
str.append("\nSale: ").append(o);
}
str.append("Buy list:");
for (Order o : buyOrderList) {
str.append("\nBuy: ").append(o);
}
return str.toString();
}
使用日志参数化调用它,如下所示:我们正在使用 java.util.logging 作为记录器.
It's called with logging parameterization like so: We're using java.util.logging as a logger.
logger.log(Level.INFO, "{0}", getOrderListAsString());
问题是,即使记录器级别为 Level.OFF
,字符串连接仍在进行中.
为了解决这个问题,我们在方法的开头添加了一个 if
语句:
The problem is that the string concatination is still being done even if the logger level is Level.OFF
.
To get around this we've added an if
statement at the start of the method:
// Declaration:
boolean shouldLog = DebugWriter.getInstance().getLogger().getLevel() != Level.OFF;
// Usage in function:
if(!shouldLog) return null;
但感觉这可以以更聪明的方式完成.提前致谢!
But it feels like this could be done in a more clever way. Thanks in advance!
推荐答案
如果您使用的是 Java 8+,那么 java.util.Logger 会重载 log
采用供应商的方法
If you are using Java 8+, then java.util.Logger has an overload of the log
method that takes a Supplier
public void log(Level level,
Supplier<String> msgSupplier)
现在,您可以制作从供应商处生成的字符串
Now, you can make the string generated from a supplier like
logger.log(Level.INFO, () -> getOrderListAsString());
或者,使用方法引用
logger.log(Level.INFO, this::getOrderListAsString);
这篇关于Java 字符串参数化 - 间接 toString 方法的性能损失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!