java 与空字符串连接以进行字符串转换真的那么糟糕吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2506474/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is concatenating with an empty string to do a string conversion really that bad?
提问by polygenelubricants
Let's say I have two charvariables, and later on I want to concatenate them into a string. This is how I would do it:
假设我有两个char变量,稍后我想将它们连接成一个字符串。这就是我将如何做到的:
char c1, c2;
// ...
String s = "" + c1 + c2;
I've seen people who say that the "" +"trick" is "ugly", etc, and that you should use String.valueOfor Character.toStringinstead. I prefer this construct because:
我见过有人说"" +“把戏”是“丑陋的”等等,你应该使用String.valueOf或Character.toString代替。我更喜欢这种结构,因为:
- I prefer using language feature instead of API call if possible
- In general, isn't the language usually more stable than the API?
- If language feature only hides API call, then even stronger reason to prefer it!
- More abstract! Hiding is good!
- I like that the
c1andc2are visually on the same levelString.valueOf(c1) + c2suggests something is special aboutc1
- It's shorter.
- 如果可能,我更喜欢使用语言功能而不是 API 调用
- 一般来说,语言通常不是比 API 更稳定吗?
- 如果语言特性只隐藏 API 调用,那么更喜欢它的理由更充分!
- 更抽象!隐身很好!
- 我喜欢
c1和c2在视觉上处于同一水平String.valueOf(c1) + c2暗示某事是特别的c1
- 它更短。
Is there really a good argument why String.valueOfor Character.toStringis preferrable to "" +?
真的有一个很好的理由为什么String.valueOf或Character.toString更可取"" +吗?
Trivia: in java.lang.AssertionError, the following line appears 7 times, each with a different type:
花絮:在 中java.lang.AssertionError,下面这行出现了 7 次,每次都有不同的类型:
this("" + detailMessage);
采纳答案by Josh Lee
Your arguments are good; this is one of the more expressive areas of the Java language, and the "" +idiom seems well entrenched, as you discovered.
你的论点很好;这是 Java 语言中"" +最具表现力的领域之一,正如您所发现的,这个习语似乎根深蒂固。
See String concatenationin the JLS. An expression like
请参阅JLS 中的字符串连接。像这样的表达
"" + c1 + c2
is equivalent to
相当于
new StringBuffer().append(new Character(c1).toString())
.append(new Character(c2).toString()).toString()
except that all of the intermediate objects are not necessary (so efficiency is not a motive). The spec says that an implementation can use the StringBufferor not. Since this feature is built into the language, I see no reason to use the more verbose form, especially in an already verbose language.
除了所有中间对象都不是必需的(因此效率不是动机)。规范说一个实现可以使用StringBuffer或不使用。由于此功能内置于语言中,我认为没有理由使用更冗长的形式,尤其是在已经很冗长的语言中。
回答by Joachim Sauer
The problem with that construct is that it usually doesn't express the intent.
该构造的问题在于它通常不表达意图。
It represents concatenation of a String with another value, but concatenation is not usually the goal of this line.
它表示字符串与另一个值的连接,但连接通常不是这一行的目标。
In the specific case that you demonstrated, concatenation is actually the goal, so this code doesexpress the intent.
在您演示的特定情况下,连接实际上是目标,因此此代码确实表达了意图。
In the more common use of this approach (String s = "" + intValue;), the concatentation is merely a tolerated side-effect, while the conversion of intValueis the actual goal. And a simple String.valueOf(intValue)expresses that intent much clearer.
在这种方法 ( String s = "" + intValue;)的更常见用法中,连接只是一种可以容忍的副作用,而转换intValue是实际目标。一个简单的String.valueOf(intValue)表达这个意图更清楚。
回答by Jon Skeet
I prefer using String.valueOffor singleconversions - but in your case you really want concatenation.
我更喜欢String.valueOf用于单次转换 - 但在你的情况下,你真的想要串联。
However, I would suggest that this version would remove all potential ambiguity:
但是,我建议这个版本会消除所有潜在的歧义:
String s = c1 + "" + c2;
That way there's no possibility, however remote, of someone considering whether c1 and c2 will be added together before the concatenation.
这样一来,无论多么遥远,都不可能有人考虑在串联之前是否将 c1 和 c2 加在一起。
回答by Bozho
I think that in "" + varthe +is actually overloaded to make the conversion:
我认为,"" + var在+实际超载进行转换:
The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method. String conversions are implemented through the method toString, defined by Object and inherited by all classes in Java. For additional information on string concatenation and conversion
Java 语言为字符串连接运算符 ( + ) 以及将其他对象转换为字符串提供了特殊支持。字符串连接是通过 StringBuilder(或 StringBuffer)类及其 append 方法实现的。字符串转换通过toString方法实现,由Object定义,Java中所有类都继承。有关字符串连接和转换的其他信息
So no difference and no problem from a technical point of view.
所以从技术角度来看没有区别也没有问题。
Form a readability point of view - it's a matter of personal preference or agreed coding style within the team.
形成可读性的观点 - 这是个人喜好或团队内部商定的编码风格的问题。
回答by mafu
In my opinion, "" + xis very readable, short, and precise to the point. I'd prefer it to longer constructs like String.valueOf. The behavior is well defined and it's so commonly in use that I find it hard to call it a hack at all.
在我看来,"" + x它非常易读、简短且准确。我更喜欢它而不是像String.valueOf. 该行为定义明确,并且在使用中是如此普遍,以至于我发现根本无法称其为 hack。
The only thing I'd be slightly worried about is performance - and am very positive that it does not matter usually (even though I did not measure or look at the binary). There is also a fair chance that this kind of concat is optimized away, since it should be easy to detect it (this is just a guess though).
我唯一会稍微担心的是性能 - 我非常肯定它通常无关紧要(即使我没有测量或查看二进制文件)。这种 concat 也很有可能被优化掉,因为它应该很容易检测到(虽然这只是一个猜测)。
回答by whiskeysierra
What about
关于什么
new String(new char[] {a, b})
and if you do it alot you could create a class "Strings" with:
如果你经常这样做,你可以创建一个“字符串”类:
public static String valueOf(char... chars) {
return new String(chars);
}
Your line would then read
你的线路然后会读
String s = Strings.valueOf(a, b);
Nice and short.
好看又短。
Edited
已编辑
A better name might be:
更好的名字可能是:
String s = Chars.asString(a, b);
回答by Chris
The "" + varstyle has one very big issue in my opinion. It just uses the toString method of the var. So if you change the type of var to something else, you will not get an exception. A nice example I just encountered was that the type was changed from intto Optional<Integer>. The code still compiles fine, but you get a completely different result.
"" + var在我看来,这种风格有一个非常大的问题。它只是使用var. 因此,如果将 var 的类型更改为其他类型,则不会出现异常。我刚刚遇到的一个很好的例子是类型从 更改int为Optional<Integer>。代码仍然可以正常编译,但您会得到完全不同的结果。
回答by Dean J
Unless your app needs every ounce of performance, write the code that's quicker to write and easier to read. "" + is a slower-to-execute syntax, but it certainly seems easier to read every time I've used it.
除非您的应用程序需要每一盎司的性能,否则请编写编写速度更快且更易于阅读的代码。"" + 是一种执行速度较慢的语法,但每次我使用它时似乎更容易阅读。
回答by Evgeniy Dorofeev
The best way to know is to compile / decompile your code, I used Jad http://en.wikipedia.org/wiki/JAD_(JAva_Decompiler) for that, you will see that your expression was converted into
最好的方法是编译/反编译你的代码,我使用了 Jad http://en.wikipedia.org/wiki/JAD_(JAva_Decompiler),你会看到你的表达式被转换成
String s = (new StringBuilder()).append("").append(ci).append(c2).toString();
String s = (new StringBuilder()).append("").append(ci).append(c2).toString();
As you can see javac actually included append("") call, but its cost is negligible, noting is appended to internal StringBuilder buffer, you can check StringBuilder's source
正如你所看到的 javac 实际上包含了 append("") 调用,但它的成本可以忽略不计,注意附加到内部 StringBuilder 缓冲区,你可以查看 StringBuilder 的源代码

