Java String vs StringBuilder

社会主义新天地 提交于 2019-12-12 05:29:17

问题


As far as i know + operator in Java String is overloaded and while we are using + operator it automatically chooses StringBuffer or StringBuilder to concatenate strings with better performance. Only exception of this is while we are using + operator inside a loop. In this case Java doesn't use benefits of StringBuffer and StringBuilder. Is that true? I will concatenate 40 Strings (around 4500 chars) and I will repeat it so often so I wanted be sure about it.


回答1:


No, Java will always (almost always, see comment bellow) convert concatenation into the StringBuilder. However the problem with loop is that it will create new instance of StringBuilder per each walkthrough.

So if you do String someString = i + "something"; inside the loop which goes from 0 to 1000 it will create for you new instance of StringBuilder 1000 times. Which could be a performance problem then. So just declare StringBuilder before the loop and then use it inside it.




回答2:


  • String is immutable while StringBuilder is mutable it means when you create a String you can never change it

  • String is thread safe while StringBuilder not

  • String stores in Constant String Pool while StringBuilder in Heap

When you loop

oldString = oldString + somechars,

it means you create a new String and put oldString`s value into it first ,then append somechars ,then redirect the oldString variable to the result



来源:https://stackoverflow.com/questions/35624421/java-string-vs-stringbuilder

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