Why is String.valueOf faster than String Concatenation for converting an Integer to a String?

六月ゝ 毕业季﹏ 提交于 2021-01-28 21:10:57

问题


This is the converse of the problem "Why is String concatenation faster than String.valueOf for converting an Integer to a String?". It is not a duplicate. Rather, it stems from this answer with benchmarks asserting that t.setText(String.valueOf(number)) is faster than t.setText(""+number), and ChristianB's question as to why that is.


回答1:


String addition results in the compiler creating a StringBuilder instance, followed by append calls for each added element, followed by a call to StringBuilder.toString() to create the resulting concatenated String instance.

So, ""+number creates a StringBuilder, appends a number using the same conversion as String.valueOf, and then creates a String instance from the StringBuilder with StringBuilder.toString.

String.valueOf(number) avoids the StringBuilder, just using the value from String.valueOf.

The answer might not be the same when the compiler can avoid all of this, if it can discern the final String result because the elements appended are all constants. In that case, the compiler just puts the final String into the compiled code.



来源:https://stackoverflow.com/questions/65709442/why-is-string-valueof-faster-than-string-concatenation-for-converting-an-integer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!