The difference between stringbuffer and stringbuilder
Whether you are working on Java or Android, you cannot avoid encountering this problem. In fact, you usually don’t struggle with it during the development process. This question is a must-have classic question in interviews. If you have time today, I will summarize it.
The difference between StringBuffer and StringBuilder
The methods and functions in StringBuffer and StringBuilder are completely equivalent, except for the methods in StringBuffer Most of them are modified with the synchronized keyword, so they are thread-safe, support concurrent operations, and are suitable for use in multi-threads. StringBuilder does not support concurrent operations, is linearly unsafe, and is not suitable for use in multi-threads. The newly introduced StringBuilder class is not thread-safe, but its performance in a single thread is higher than StringBuffer. (Recommended learning: JAVA video tutorial)
Next, I directly paste the code of the test process and results, which is clear at a glance:
public class StringTest { public static String BASEINFO = "Mr.Y"; public static final int COUNT = 2000000; /** * 执行一项String赋值测试 */ public static void doStringTest() { String str = new String(BASEINFO); long starttime = System.currentTimeMillis(); for (int i = 0; i < COUNT / 100; i++) { str = str + "miss"; } long endtime = System.currentTimeMillis(); System.out.println((endtime - starttime) + " millis has costed when used String."); } /** * 执行一项StringBuffer赋值测试 */ public static void doStringBufferTest() { StringBuffer sb = new StringBuffer(BASEINFO); long starttime = System.currentTimeMillis(); for (int i = 0; i < COUNT; i++) { sb = sb.append("miss"); } long endtime = System.currentTimeMillis(); System.out.println((endtime - starttime) + " millis has costed when used StringBuffer."); } /** * 执行一项StringBuilder赋值测试 */ public static void doStringBuilderTest() { StringBuilder sb = new StringBuilder(BASEINFO); long starttime = System.currentTimeMillis(); for (int i = 0; i < COUNT; i++) { sb = sb.append("miss"); } long endtime = System.currentTimeMillis(); System.out.println((endtime - starttime) + " millis has costed when used StringBuilder."); } /** * 测试StringBuffer遍历赋值结果 * * @param mlist */ public static void doStringBufferListTest(List<String> mlist) { StringBuffer sb = new StringBuffer(); long starttime = System.currentTimeMillis(); for (String string : mlist) { sb.append(string); } long endtime = System.currentTimeMillis(); System.out.println(sb.toString() + "buffer cost:" + (endtime - starttime) + " millis"); } /** * 测试StringBuilder迭代赋值结果 * * @param mlist */ public static void doStringBuilderListTest(List<String> mlist) { StringBuilder sb = new StringBuilder(); long starttime = System.currentTimeMillis(); for (Iterator<String> iterator = mlist.iterator(); iterator.hasNext();) { sb.append(iterator.next()); } long endtime = System.currentTimeMillis(); System.out.println(sb.toString() + "builder cost:" + (endtime - starttime) + " millis"); } public static void main(String[] args) { doStringTest(); doStringBufferTest(); doStringBuilderTest(); List<String> list = new ArrayList<String>(); list.add(" I "); list.add(" like "); list.add(" BeiJing "); list.add(" tian "); list.add(" an "); list.add(" men "); list.add(" . "); doStringBufferListTest(list); doStringBuilderListTest(list); } }
Look at the execution results:
2711 millis has costed when used String. 211 millis has costed when used StringBuffer. 141 millis has costed when used StringBuilder. I like BeiJing tian an men . buffer cost:1 millis I like BeiJing tian an men . builder cost:0 millis
As can be seen from the above results, regardless of multi-threading, when using String objects (I put Count/100), the execution time is longer than the other two. High, and the difference between using StringBuffer objects and using StringBuilder objects is also obvious. It can be seen that if our program is running in a single thread, or there is no need to consider thread synchronization issues, we should give priority to using the StringBuilder class; if we want to ensure thread safety, it is naturally StringBuffer.
It can be seen from the test results of the following List that except for the different support for multi-threading, there is almost no difference in the usage and results of these two classes.
For more JAVA related technical articles, please visit the JAVA Development Tutorial column to learn!
The above is the detailed content of The difference between stringbuffer and stringbuilder. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

StringBuffer objects are generally safe to use in multi-threaded environments, where multiple threads may try to access the same StringBuffer object simultaneously. StringBuilder is a thread-safe replacement for the StringBuffer class that works much faster because it has no synchronized > methods. If we perform a lot of string operations in a single thread, using this class can improve performance. Example publicclassCompareBuilderwithBufferTest{ publicstaticvoidmain(String[]a

Convert a StringBuffer to a string using the toString() method of the StringBuffer class. In Java, the StringBuffer class is a class used to handle mutable strings. It provides many convenient methods to modify and manipulate strings. When we need to convert a StringBuffer object into a string, we can use the toString() method to achieve this. The toString() method of the StringBuffer class returns a

Use the reverse() method of the StringBuffer class to reverse a string. In programming, we often need to perform some operations on strings, such as reversing strings. In Java, you can use the reverse() method of the StringBuffer class to achieve string reversal. Let's take a look at the use of this method. First, we need to create a StringBuffer object and pass the string to be reversed as a parameter to its constructor as shown below

Basic concepts of the String class The String class is a reference data type, not a basic data type. In Java, as long as it is enclosed in "" (double quotes), it is a String object. Java stipulates that strings in double quotes are immutable, which means that "abc" cannot become "abcd" or "ab" from birth to death. In the JDK, strings enclosed in double quotes are stored in the string constant pool in the method area. (Because in actual development, strings are used very frequently, for the sake of execution efficiency, strings are placed in the string constant pool in the method area.

Use the substring() method of the StringBuffer class to obtain a substring of part of a string. In Java programming, it is often necessary to process and operate strings. The StringBuffer class is a commonly used string class that provides a series of convenient methods to operate strings. Among them, the substring() method is a very commonly used method, which can be used to obtain part of the content of a string, that is, a substring. The following will introduce how to use the StringBuffer class

When modifying strings, you need to use the StringBuffer and StringBuilder classes. Unlike the String class, objects of the StringBuffer and StringBuilder classes can be modified multiple times without creating new unused objects. StringBuffer: When using the StringBuffer class, the StringBuffer object itself will be operated every time instead of generating a new object, so it is recommended to use StringBuffer if you need to modify the string. StringBuilder: The StringBuilder class was proposed in Java5, and it is similar to S

Use the insert() method of the StringBuffer class to insert content into a string in Java. In Java programming, the StringBuffer class is a very commonly used string manipulation class. It provides a variety of methods to modify strings, among which the insert() method is a very convenient method for inserting content into a string. The function of the insert() method is to insert a character, a character array, a string or a string converted from other data types at the specified position.

Reverse the order of characters in a string using reverse() method of StringBuffer class In Java, there are various ways to reverse the order of characters in a string. One of the simple and efficient methods is to use the reverse() method of the StringBuffer class. This article will introduce how to use this method to reverse strings and provide relevant code examples. StringBuffer class is a mutable class in Java used for processing strings. Unlike the String class,
