Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 233
user253122 Avatar asked Apr 15 '17 14:04

user253122


2 Answers

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.

like image 80
Jacob G. Avatar answered Oct 27 '22 08:10

Jacob G.


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.)

like image 23
D M Avatar answered Oct 27 '22 09:10

D M