Home > Java > JavaBase > body text

The difference between string, stringbuffer and stringbuilder

hzc
Release: 2020-06-19 17:24:55
Original
2755 people have browsed it

The difference between string, stringbuffer and stringbuilder

What are the differences between string, stringbuffer and stringbuilder?

In a phone interview, the editor was asked whether StringBuilder is thread-safe. It's safe to blurt out, but people question me if you have 2 years of development experience. Not using this class for a long time caused me to forget my choice. It can also be said that the foundation is not strong. I don’t know if any of you have had such an experience, so I’d better record it in writing to enhance my memory.

String: Everyone knows that String is modified with final, so its value is immutable. This results in a new String object being generated every time an operation is performed on String. This is not only inefficient, but also a large number of Waste of limited memory space, as shown in the figure:

The difference between string, stringbuffer and stringbuilder

We can see that the initial String value is "abc", and then add a new string after this string " bv", this process requires re-opening memory space in the stack memory. Finally, the "abcbv" string needs to be opened up memory space accordingly. Such short two strings need to open up memory space three times. I have to say that this is a huge waste of memory space. In order to deal with frequent string-related operations, two new classes—StringBuffer class and StringBuild class—were introduced to handle such changing strings.

The difference between string, stringbuffer and stringbuilder

StringBuilder class: proposed in Java 5, characterized by mutable strings. High execution efficiency and thread unsafe.

StringBuffer class: characterized by variable strings, low execution efficiency, and thread safety.

It can be seen that the time is faster.

Summary:

  • If you want to operate a small amount of data, use String;

  • Multi-threaded operation string buffer operation A large amount of data StringBuffer;

  • Single-threaded operation string buffer to operate a large amount of data StringBuilder.

Recommended tutorial: "java tutorial"

The above is the detailed content of The difference between string, stringbuffer and stringbuilder. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template