Difference between string stringbuilder and stringbuffer

Source: Internet
Author: User

This article references http://wenku.baidu.com/view/8de1a06b011ca300a6c390d2.html

1. String Class Object

A. Once created, it cannot be changed.

B. If you assign a new value to a referenced object, but direct the new reference to a new object, the old object remains unchanged. (That is, each time a new value is assigned, a new object is created)

2. stringbuffer, stringbuilder:

A. The object content can be modified. Each operation will operate on the object itself, rather than generating a new object.

3. The following is a test of the class.

package com.jue.test;public class MainTest {public static void main(String[] args) {test1();// 1685test2();// 12}private static void test1() {long startTime = System.currentTimeMillis();String s = "abc";for (int i = 0; i < 10000; i++) {s += "123";}long currentTime = System.currentTimeMillis();System.out.println(currentTime - startTime);}private static void test2() {long startTime = System.currentTimeMillis();StringBuffer s = new StringBuffer("abc");for (int i = 0; i < 10000; i++) {s.append("123");}long currentTime = System.currentTimeMillis();System.out.println(currentTime - startTime);}}

Result

Test 1: 1685

Test2: 12

4. In some cases, directly adding is faster than stringbuffer

private static void test3() {long startTime = System.currentTimeMillis();StringBuilder s = new StringBuilder("abc");for (int i = 0; i < 10000000; i++) {s.append("123");}long currentTime = System.currentTimeMillis();System.out.println(currentTime - startTime);}private static void test4() {long startTime = System.currentTimeMillis();for (int i = 0; i < 10000; i++) {String s1 = "123" + "456" + "789" + "abc" + "def";}long currentTime = System.currentTimeMillis();System.out.println(currentTime - startTime);}

Result:

Test3: 0 ~ 1

Test4: 80 ~ 90

5. stringbuffer and stringbuilder

Stringbuffer is thread-safe.

Stringbuilder is non-thread-safe. It is better to use stringbuilder if there is no thread escape.

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.