Why still use String instead of Stringbuilder in Java?

Asked

Viewed 94 times

1

As many of you may already know, creating StringBuilder can greatly save the performance of our Java applications, as they are much faster than a String.

This is due to the fact that the StringBuilder is changeable differently from String, that creates new objects with each concatenation that we make.

My question is, why is it still used String in Java? Why shouldn’t we just use the StringBuilder in our applications?

  • 1

    In a way, reading over me seems to me that it is well answered here already: String and its efficiency including links to deepen more about Stringbuilder and Stringbuffer.

  • I read that question before I asked mine. Only in this issue it only talks about what is Stringbuilder and what is String. I am looking for something more in-depth about whether a String is really still useful (a comparison between String and Stringbuffer and not their definition).

  • 1

    There is an option, when you offer bonus on a question, that is to ask for answer with more details: https://i.stack.Imgur.com/Kfmmx.png

1 answer

6


As many of you may already know, creating StringBuilder can greatly save the performance of our Java applications, as they are much faster than a String.

They are not, there were even times that SB was worse in some scenarios, I do not know what still happens this because this kind of thing is implementation detail.

This is due to the fact that the StringBuilder is changeable differently from String, that creates new objects with each concatenation that we make.

Only in this case it gets faster. The name says it all, this type only serves to build a string.

Why is it still used String in Java? Why shouldn’t we just use the StringBuilder in our applications?

Because in the vast majority of cases we don’t make mutations in string. And people will start abusing the mutability of texts where they don’t need.

And because mutable objects don’t work well in concurrent environment, which is increasingly common, it would complicate the entire application having to deal with it.

It is still common maps (dictionaries, tables hash) use strings as key, and keys need immutable data to work well (a change needs to reorganize whole map).

Reflection also has similar problems in some scenarios.

And mutable data do not get along well with cache, and still hinder reuse by interning.

From a security point of view it is easier to make undue access in a string mutable.

Not to mention the object stringBuilder is more complex internally.

Nor did I get into the merit that can no longer change with the car walking. The current class is extremely limited. It needs to change a lot what already exists to have the same power and flexibility as String. And all current Apis accept String, nay StringBuilder.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.