简体   繁体   English

“带有char的字符串:”+'c'比带有char的字符串更好或更差:“+ c”?

[英]“a string with a char: ” + 'c' better or worse than “a string with a char: ” + “c”?

A small question, but one I'm genuinely curious about. 一个小问题,但我真的很好奇。

Is there anything inherently better or worse with 有什么本质上更好或更糟的

"a string with a char: " + 'x'

compared to 相比

"a string with a char: " + "x"

?

They both work, but I am wondering if either has any performance or efficiency implications--minor as they may be. 它们都有效,但我想知道是否有任何性能或效率影响 - 尽管它们可能很小。

Thanks. 谢谢。

public void test(){ 
    String str1 = "appl" + 'e';
    String str2 = "banan" + "a";
}

No change in byte code: 字节代码没有变化:

public void test();
    Code:
       0: ldc           #2                  // String apple
       2: astore_1      
       3: ldc           #3                  // String banana
       5: astore_2      
       6: return

I should mention that if you put the concatenation in a loop then StringBuilder will be used for both. 我应该提一下,如果你将串联放在循环中,那么StringBuilder将用于两者。 That's all. 就这样。

I am very sure that they will both generate the same efficient bytecode. 我非常确定它们都会生成相同的高效字节码。 Compilers are clever 编译器很聪明

So if there would be a difference (which I am not sure of), the compiler will erase it 因此,如果存在差异(我不确定),编译器将擦除它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM