String, stringbuffer, stringbuilder

Source: Internet
Author: User

String is an immutable class, and JVM is usually optimized for common classes. For example, there is a string pool for string.
During the string connection operation, do not use "+", and the application uses stringbuffer instead. Of course, if there are few connections, replace it with "+.
I have tested and performed 10000 "+" operations and stringbuffer. append operations. The time consumed by the two operations is almost an order of magnitude.
Generally, the former may take several hundred thousands of Ms while the latter may take 0 ms.
When I increase the number of tests to 10000*10, the former usually takes several minutes or even tens of minutes, while the latter generally completes quickly.
Why is this difference?
You can think about it. String is an immutable class, so a new object is generated for each connection.
100,000 operations as I did above would generate 100,000 objects. In this way, even if efficiency is not considered,
Memory overhead is also extremely undesirable.

 

In jdk5.0, A stringbuilder class is added, which is the same as stringbuffer. The only difference is that stringbuffer is thread-safe, and stringbuilder is NOT thread-safe.
Compare the differences between the two. Write a small program and test it. The problem can be seen when two threads access the program at the same time.
The test result is generally stringbuffer that produces the correct result. stringbuilder may encounter exceptions (sometimes outofmemoryexception) or result errors.

As stringbuffer synchronizes threads, in a single-threaded environment, stringbuilder is more efficient than stringbuffer.
Use stringbuffer in a multi-threaded environment. Otherwise, stringbuilder is strongly recommended.

For example, you can use stringbuilder in some tool classes and local variables, because local variables do not involve concurrent access at all.
Generally, stringbuilder is recommended unless stringbuffer is used as a class variable or instance variable.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.