是否使用("" +< int value>)转换为字符串错误做法? [英] Is conversion to String using ("" + <int value>) bad practice?
问题描述
使用
"" + <int value>
不良做法?与 String.valueOf(...)相比,它有任何缺点吗?
bad practice? Does it have any drawbacks compared to String.valueOf(...)?
代码示例:
int i = 25;
return "" + i;
vs:
int i = 25;
return String.valueOf(i);
更新(来自评论)
那么 Integer.toString(int i)与 String.valueOf(...)相比呢?
推荐答案
我总是更喜欢 String.valueOf
版本:主要是因为它显示了你想要的东西做。目标不是字符串连接 - 它是转换为字符串,字符串值 i
。
I would always prefer the String.valueOf
version: mostly because it shows what you're trying to do. The aim isn't string concatenation - it's conversion to a string, "the string value of i
".
第一种形式也可能效率低下 - 取决于编译器是否发现了您正在做的事情。如果没有,它可能会创建一个新的StringBuffer或StringBuilder并附加该值,然后将其转换为字符串。
The first form may also be inefficient - depending on whether the compiler spots what you're doing. If it doesn't, it may be creating a new StringBuffer or StringBuilder and appending the value, then converting it to a string.
有趣的是,我有一个关于这个主题的文章 - 多年前写的;我网站上的第一篇Java文章之一,IIRC。
Funnily enough, I have an article about this very topic - written years and years ago; one of the first Java articles on my web site, IIRC.
这篇关于是否使用("" +< int value>)转换为字符串错误做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!