哪种引号效率更高?
只是好奇,哪个更有效率?
这个:
String a = someString + "." + anotherString;
或者这个:
String a = someString + '.' + anotherString;
Just curious, which is more efficient?
This:
String a = someString + "." + anotherString;
Or this:
String a = someString + '.' + anotherString;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你真的不应该在意,除非这就是你所做的一切,每秒数千次,持续几个小时。
有传言说使用 StringBuilder 是最快的。
尝试一下它们,循环运行一百万次,并记录所需的时间,然后向我们其他人报告。
You really shouldn't care, unless this is all you do, thousands of times per second, for several hours.
Rumor has it that using a StringBuilder is the fastest.
Try it both of them, running in a loop, a million times, and logging the time it takes, then report back to the rest of us.
查看
StringBuilder.append
和AbstractStringBuilder.append
的代码,我期望 '.'形式更快。基本上,它要做的事情较少:
不过,像其他人一样,我不希望在实际应用程序代码中差异很大。
我不知道 Java 编译器认识到附加的内容是长度为 1 的常量字符串并将其转换为字符文字是否有效 - 或者即使它有效,它是否会麻烦这样做。
Looking at the code for
StringBuilder.append
andAbstractStringBuilder.append
, I would expect the '.' form to be faster.It has less to do, basically:
Like everyone else though, I wouldn't expect the difference to be significant in real application code.
I don't know whether it would be valid for the Java compiler to realise that what's being appended is a constant string of length 1, and convert that into a character literal instead - or whether it would bother doing so even if it would be valid.
它们非常相似。
'.'
稍快一些,但差异可以忽略不计(在 1000 万次循环中大约需要 20 毫秒)。这是我的测试:
您可以进行平均和/或创建更复杂的测试。
无论如何,他们都在内部使用 StringBuilder 。
They are pretty similar.
'.'
is slightly faster, but the difference is negligible ( about 20 ms in a 10 million loop ) .Here's my test:
You can do an average and/or create a more complex test.
They both use StringBuilder internally anyway.
Java 编译器会将任何字符串连接表达式转换为等效的 StringBuilder 操作序列。可以肯定地假设该序列将接近最优。事实上,在这个特定的示例中,我希望在这两种情况下都会生成相同的(最佳)序列。但即使情况并非如此,差异也可能很小。
只有当探查器告诉您某个特定语句是代码中的瓶颈时,才值得担心此类事情。过早的优化(充其量)是毫无意义的,甚至可能是有害的。
Sun 人员的建议是,手动优化 Java 代码实际上可能会变慢,因为生成的字节码序列变得过于复杂,以至于 JIT 编译器无法正确优化。最好的建议是简单地编写代码并相信 Javac 和 JIT 编译器可以很好地完成工作。
The Java compiler will turn any string concatenation expression into an equivalent sequence of StringBuilder operations. It is safe to assume that the sequence will be close to optimal. Indeed, in this particular example, I'd expect the same (optimal) sequence to be generated in both cases. But even if this is not the case, the difference is likely to be small.
It is only worth bothering about this sort of thing if the profiler tells you that a particular statement is a bottleneck in your code. Premature optimization is pointless (at best) and can even be harmful.
The advice of the Sun folks is that hand optimize Java code can actually be slower code because the resulting bytecode sequence becomes too complex for the JIT compiler to be able to optimize properly. The best advice is just to write the code simply and trust the Javac and JIT compilers to do a good job.