Java StringBuilder. Setlength() – is the time complexity O (1)?

I'm going to do a lot of deleting the last character in stringbuilders Use sb Setlength solution (sb. Length() – 1); It looks good to me However, since these deletions will be in a loop, I need to know its complexity

The way I understand it is that this operation simply reduces some private properties of my StringBuilder object and does not perform any copy / clone / copy of the character itself, so it is O (1) timely and should work quickly

Am I right?

Solution

From document:

I'll say yes But from the perspective of time complexity, I won't see it The reason we use StringBuilder instead of string in the loop is because the string is immutable Therefore, when we try to change it, a new string object will always be created Changing the length of a StringBuilder object does not create a new object

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>