What is the time complexity of StringBuilder.append() in java?

拈花ヽ惹草 提交于 2020-12-08 07:08:39

问题


A program I'm working on converts an array of integers to a string using string builder. I'm trying to determine the time complexity of this approach.


回答1:


Check out: https://stackoverflow.com/a/7156703/7294647

Basically, it's not clear what the time complexity is for StringBuilder#append as it depends on its implementation, so you shouldn't have to worry about it.

There might be a more efficient way of approaching your int[]-String conversion depending on what you're actually trying to achieve.




回答2:


If the StringBuilder needs to increase its capacity, that involves copying the entire character array to a new array. You can avoid this by initially setting the capacity so it won't have to do this. (This should be easy since you know the length of the int array and the maximum number of characters in the String representation of an int.)

If you avoid the need to increase the capacity, the complexity would seem to just be O(n). When you append, you're just copying the character array from the String to the end of the character array in the StringBuilder.

(Yes, it depends on the implementation, but it would be a rather poor implementation of StringBuilder if it couldn't append in O(n) time.)



来源:https://stackoverflow.com/questions/43427233/what-is-the-time-complexity-of-stringbuilder-append-in-java

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