2

If I have a StringBuilder object sb, what's the time complexity when I try to create a new string with the code new String(sb)? See below for an example. Should it be O(n) since it creates a string with a deep copy of the original sb? Thanks.

StringBuilder sb = new StringBuilder();
sb.append('a');
sb.append('b');
String c = new String(sb);
1
  • Don't try to trick people into viewing your question by applying irrelevant language tags. Commented Oct 20, 2022 at 0:58

1 Answer 1

3

Yup. O(n). That's why it's in the library. The same is true for C#.

Strings, in both languages, are immutable. So building reports and other text documents with successive string concatenation is O(n squared).

The developers for the StringBuilder class in both languages have invested a lot of brain power and testing time in making it really fast. The same is true for the other core collection classes of course.

If you can refactor some successive concatenation code with StringBuilder code, you will become revered as a performance optimization wizard.

Beware StringBuffer. It has similar semantics but it happens to be thread safe, which slows it down a lot.

Sign up to request clarification or add additional context in comments.

1 Comment

The use of StringBuffer is a code smell. Prefer stateless threadsafe code and using StringBuilder.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.