问题描述
使用{}
代替字符串串联是否有任何优势?
Is there any advantage of using {}
instead of string concatenation?
来自slf4j的示例
logger.debug("Temperature set to {}. Old temperature was {}.", t, oldT);
代替
logger.debug("Temperature set to"+ t + ". Old temperature was " + oldT);
我认为这与速度优化有关,因为可以根据配置文件在运行时避免参数评估(和字符串连接).但是只有两个参数是可能的,因此有时除了字符串串联外别无选择.需要对此问题的看法.
I think it's about speed optimization because parameters evaluation (and string concatenation) could be avoided in runtime depending on a config file. But only two parameters are possible, then sometimes there is no other choice than string concatenation. Needing views on this issue.
推荐答案
是有关字符串连接性能的信息.如果您有密集的日志记录语句,这可能很重要.
It is about string concatenation performance. It's potentially significant if your have dense logging statements.
由于绝大多数日志记录语句具有2个或更少的参数,因此,版本1.6以下的SLF4J API(仅)涵盖了大多数用例.从API版本1.7开始,API设计人员就提供了带有varargs参数的重载方法.
Because the vast majority of logging statements have 2 or fewer parameters, so SLF4J API up to version 1.6 covers (only) the majority of use cases. The API designers have provided overloaded methods with varargs parameters since API version 1.7.
对于那些需要2个以上且被1.7版SLF4J困扰的情况,则只需使用字符串串联或new Object[] { param1, param2, param3, ... }
.应该有足够的数量,使性能不那么重要.
For those cases where you need more than 2 and you're stuck with pre-1.7 SLF4J, then just use either string concatenation or new Object[] { param1, param2, param3, ... }
. There should be few enough of them that the performance is not as important.
这篇关于Logger slf4j使用{}格式化而不是字符串连接的优点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!