Logger slf4j 使用 {} 格式化而不是字符串连接的优点 [英] Logger slf4j advantages of formatting with {} instead of string concatenation

查看:22
本文介绍了Logger slf4j 使用 {} 格式化而不是字符串连接的优点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 {} 代替字符串连接有什么好处吗?

Is there any advantage of using {} instead of string concatenation?

来自 slf4j 的示例

An example from 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.

(在 SLF4J 1.7 之前)但只有两个参数是可能的

(Prior to SLF4J 1.7) But only two parameters are possible

因为绝大多数日志语句都有 2 个或更少的参数,所以 SLF4J API 直到 1.6 版才涵盖(仅)大多数用例.从 API 1.7 版开始,API 设计者就提供了带有可变参数参数的重载方法.

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 使用 {} 格式化而不是字符串连接的优点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆