java 字符串 valueOf 与空字符串的连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7752347/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 21:16:41  来源:igfitidea点击:

String valueOf vs concatenation with empty string

java

提问by Cool Java guy ?????

I am working in Java code optimization. I'm unclear about the difference between String.valueOfor the +""sign:

我从事 Java 代码优化工作。我不清楚两者之间的区别String.valueOf+""标志:

int intVar = 1;
String strVar = intVar + "";
String strVar = String.valueOf(intVar);

What is the difference between line 2 and 3?

第 2 行和第 3 行有什么区别?

回答by Jigar Joshi

public void foo(){
int intVar = 5;
String strVar = intVar+"";    
}

This approach uses StringBuilder to create resultant String

这种方法使用 StringBuilder 创建结果字符串

public void foo();
  Code:
   0:   iconst_5
   1:   istore_1
   2:   new     #2; //class java/lang/StringBuilder
   5:   dup
   6:   invokespecial   #3; //Method java/lang/StringBuilder."<init>":()V
   9:   iload_1
   10:  invokevirtual   #4; //Method java/lang/StringBuilder.append:(I)Ljava/lan
g/StringBuilder;
   13:  ldc     #5; //String
   15:  invokevirtual   #6; //Method java/lang/StringBuilder.append:(Ljava/lang/
String;)Ljava/lang/StringBuilder;
   18:  invokevirtual   #7; //Method java/lang/StringBuilder.toString:()Ljava/la
ng/String;
   21:  astore_2
   22:  return


public void bar(){
int intVar = 5;
String strVar = String.valueOf(intVar);
}

This approach invokes simply a static method of Stringto get the String version of int

这种方法简单地调用了一个静态方法String来获取 int 的 String 版本

public void bar();
  Code:
   0:   iconst_5
   1:   istore_1
   2:   iload_1
   3:   invokestatic    #8; //Method java/lang/String.valueOf:(I)Ljava/lang/Stri
ng;
   6:   astore_2
   7:   return

which in turn calls Integer.toString()

反过来调用 Integer.toString()

回答by Jon Skeet

Ask yourself the purpose of the code. Is it to:

问问自己代码的目的。是不是:

  • Concatenate an empty string with a value
  • Convert a value to a string
  • 将一个空字符串与一个值连接起来
  • 将值转换为字符串

It sounds much more like the latter to me... which is why I'd use String.valueOf. Whenever you can make your code read in the same way as you'd describe what you want to achieve, that's a good thing.

对我来说听起来更像是后者......这就是为什么我会使用String.valueOf. 每当您能够以与描述您想要实现的目标相同的方式阅读您的代码时,这是一件好事。

Note that this works for all types, and will return "null" when passed a null reference rather than throwing a NullPointerException. If you're using a class (not an intas in this example) and you wantit to throw an exception if it's null (e.g. because that represents a bug), call toStringon the reference instead.

请注意,这适用于所有类型,并且在传递空引用而不是抛出NullPointerException. 如果您正在使用一个类(不是int本例中的an )并且您希望它在它为 null 时抛出异常(例如,因为它代表一个错误),请toString改为调用该引用。

回答by duffymo

I'd prefer valueOf(), because I think it's more readable and explicit.

我更喜欢valueOf(),因为我认为它更具可读性和明确性。

Any concerns about performance are micro-optimizations that wouldn't be measurable. I wouldn't worry about them until I could take a measurement and see that they made a difference.

任何对性能的担忧都是无法衡量的微观优化。在我可以进行测量并看到它们有所作为之前,我不会担心它们。

回答by Peter Lawrey

Using String.valueOf(int), or better, Integer.toString(int)is relatively more efficient for the machine. However, unless performance is critical (in which case I wouldn't suggest you use either) Then ""+ xis much more efficient use of your time. IMHO, this is usually more important. Sometimes massively more important.

使用String.valueOf(int),或者更好,Integer.toString(int)对于机器来说相对更有效。但是,除非性能至关重要(在这种情况下,我不建议您使用任何一种),否则可以""+ x更有效地利用您的时间。恕我直言,这通常更重要。有时更重要。

In other words, ""+wastes an object, but Integer.toString()creates several anyway. Either your time is more important or you want to avoid creating objects at all costs. You are highly unlikely to be in the position that creating several objects is fine, but creating one more is not.

换句话说,""+浪费了一个对象,但Integer.toString()无论如何创建了几个。要么您的时间更重要,要么您想不惜一切代价避免创建对象。您极不可能处于创建多个对象很好的位置,但再创建一个对象则不然。

回答by Thilo

The first line is equivalent to

第一行相当于

String strVal = String.valueOf(intVar) + "";

so that there is some extra (and pointless) work to do. Not sure if the compiler optimizes away concatenations with empty string literals. If it does not (and looking at @Jigar's answer it apparently does not), this will in turn become

所以有一些额外的(和毫无意义的)工作要做。不确定编译器是否优化了与空字符串文字的连接。如果没有(并且查看@Jigar 的答案显然没有),这将反过来成为

String strVal = new StringBuilder().append(String.valueOf(intVar))
                      .append("").toString();

So you should really be using String.valueOf directly.

所以你真的应该直接使用 String.valueOf 。

回答by Bhaskar

From the point of optimization , I will always prefer the String.valueOf()between the two. The first one is just a hack , trying to trick the conversion of the intVarinto a Stringbecause the + operator.

从优化的角度来看,我总是更喜欢两者String.valueOf()之间的。第一个只是一个 hack ,试图欺骗转换intVar为 aString因为 + 运算符。

回答by Michael Borgwardt

Concatenating Strings and other variables actually uses String.valueOf()(and StringBuilder) underneath, so the compiler will hopefully discard the empty String and produce the same bytecodes in both cases.

连接字符串和其他变量实际上在下面使用String.valueOf()(和StringBuilder),因此编译器有望丢弃空字符串并在两种情况下生成相同的字节码。

回答by esin88

Even though answers here are correct in general, there's one point that is not mentioned.

尽管这里的答案总体上是正确的,但有一点没有被提及。

"" + intVarhas better performance compared to String.valueOf()or Integer.toString(). So, if performance is critical, it's better to use empty string concatenation.

"" + intVarString.valueOf()或相比具有更好的性能Integer.toString()。因此,如果性能至关重要,最好使用空字符串连接。

See this talkby Aleksey Shipil?v. Or these slidesof the same talk (slide #24)

请参阅Aleksey Shipil?v 的这篇演讲。或者相同演讲的这些幻灯片(幻灯片 #24)

回答by Jitesh Singh

Well, if you look into the JRE source code, Integer.getChars(...)is the most vital method which actually does the conversion from integer to char[], but it's a package-private method.
So the question is how to get this method called with minimum overhead.
Following is an overview of the 3 approaches by tracing the calls to our target method, please look into the JRE source code to understand this better.

好吧,如果您查看 JRE 源代码,Integer.getChars(...)它实际上是将整数转换为 char[] 的最重要方法,但它是一个包私有方法。
所以问题是如何以最小的开销调用这个方法。
以下是通过跟踪对目标方法的调用对 3 种方法的概述,请查看 JRE 源代码以更好地理解这一点。

  1. "" + intVarcompiles to :
    new StringBuilder()=> StringBuilder.append(int)=> Integer.getChars(...)
  2. String.valueOf(intVar)=> Integer.toString(intVar)=> Integer.getChars(...)
  3. Integer.toString(intVar)=> Integer.getChars(...)
  1. "" + intVar编译为:
    new StringBuilder()=> StringBuilder.append(int)=>Integer.getChars(...)
  2. String.valueOf(intVar)=> Integer.toString(intVar)=>Integer.getChars(...)
  3. Integer.toString(intVar)=> Integer.getChars(...)

The first method unnecessarily creates one extra object i.e. the StringBuilder.
The second simply delegates to third method.
So you have the answer now.

第一种方法不必要地创建了一个额外的对象,即 StringBuilder。
第二个简单地委托给第三个方法。
所以你现在有了答案。

PS: Various compile time and runtime optimizations come into play here. So actual performance benchmarks may say something else depending on different JVM implementations which we can't predict, so I generally prefer the approach which looks efficient by looking at the source code.

PS:各种编译时间和运行时优化在这里发挥作用。因此,实际性能基准测试可能会根据我们无法预测的不同 JVM 实现来说明其他内容,因此我通常更喜欢通过查看源代码看起来有效的方法。

回答by Racooon

String strVar1 = intVar+"";
String strVar2 = String.valueOf(intVar);

strVar1 is equvalent to strVar2, but using int+emptyString "" is not elegant way to do it.

strVar1 等效于 strVar2,但使用 int+emptyString "" 并不是一种优雅的方式。

using valueOf is more effective.

使用 valueOf 更有效。