search
HomeJavajavaTutorialThe 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 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  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);
	}
 
}</string></string></string></string>

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!

Statement
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
在Java中,我们如何比较StringBuilder和StringBuffer?在Java中,我们如何比较StringBuilder和StringBuffer?Aug 28, 2023 pm 03:57 PM

StringBuffer对象通常可以安全地在多线程环境中使用,其中多个线程可能会尝试访问同一个StringBuffer对象同时。StringBuilder是线程安全的StringBuffer类的替代品,它的工作速度要快得多,因为它没有同步>方法。如果我们在单个线程中执行大量字符串操作,则使用此类可以提高性能。示例publicclassCompareBuilderwithBufferTest{&nbsp;&nbsp;publicstaticvoidmain(String[]a

使用StringBuffer类的reverse()方法来反转字符串使用StringBuffer类的reverse()方法来反转字符串Jul 24, 2023 pm 04:41 PM

使用StringBuffer类的reverse()方法来反转字符串在编程中,我们经常需要对字符串进行一些操作,例如反转字符串。在Java中,可以使用StringBuffer类的reverse()方法来实现字符串反转。下面让我们一起来了解一下这个方法的使用。首先,我们需要创建一个StringBuffer对象,将要反转的字符串作为参数传递给它的构造函数,如下所示

使用StringBuffer类的toString()方法将StringBuffer转换为字符串使用StringBuffer类的toString()方法将StringBuffer转换为字符串Jul 25, 2023 pm 06:45 PM

使用StringBuffer类的toString()方法将StringBuffer转换为字符串在Java中,StringBuffer类是用于处理可变字符串的类,它提供了许多方便的方法来修改和操作字符串。当我们需要将一个StringBuffer对象转换为字符串时,可以使用toString()方法来实现。StringBuffer类的toString()方法返回一

Java中StringBuffer和StringBuilder怎么使用Java中StringBuffer和StringBuilder怎么使用Jun 02, 2023 pm 03:01 PM

当对字符串进行修改的时候,需要使用StringBuffer和StringBuilder类。和String类不同的是,StringBuffer和StringBuilder类的对象能够被多次的修改,并且不产生新的未使用对象。StringBuffer:在使用StringBuffer类时,每次都会对StringBuffer对象本身进行操作,而不是生成新的对象,所以如果需要对字符串进行修改推荐使用StringBuffer。StringBuilder:StringBuilder类在Java5中被提出,它和S

使用StringBuffer类的insert()方法在Java中向字符串中插入内容使用StringBuffer类的insert()方法在Java中向字符串中插入内容Jul 24, 2023 am 11:34 AM

使用StringBuffer类的insert()方法在Java中向字符串中插入内容在Java编程中,StringBuffer类是一个非常常用的字符串操作类。它提供了多种方法来修改字符串,其中insert()方法是一种非常方便用于向字符串中插入内容的方法。insert()方法的作用是在指定的位置插入一个字符、一个字符数组、一个字符串或者其他数据类型转化的字符串

如何在Java中使用String类、StringBuffer和StringBuilder?如何在Java中使用String类、StringBuffer和StringBuilder?Apr 21, 2023 pm 07:22 PM

String类基本概念String类属于引用数据类型,不属于基本数据类型。在Java中只要是""(双引号)中的,都是String对象。java中规定,双引号中的字符串是不可变的,也就是说"abc"自出生到死亡都不可能变成"abcd",也不能变成"ab"。在JDK中双引号括起来的字符串都是存储在方法区的字符串常量池当中的。(因为在实际开发中,字符串的使用频率十分高,为了执行效率,就把字符串放在了方法区中的字符串常量池当

使用StringBuffer类的reverse()方法反转字符串中的字符顺序使用StringBuffer类的reverse()方法反转字符串中的字符顺序Jul 26, 2023 pm 10:10 PM

使用StringBuffer类的reverse()方法反转字符串中的字符顺序在Java中,有多种方法可以反转字符串中的字符顺序。其中一个简单而高效的方法是使用StringBuffer类的reverse()方法。本文将介绍如何使用这个方法来实现字符串反转,并提供相关的代码示例。StringBuffer类是Java中用于处理字符串的可变类。与String类不同,

使用StringBuffer类的substring()方法获取字符串部分内容的子串使用StringBuffer类的substring()方法获取字符串部分内容的子串Jul 24, 2023 pm 12:41 PM

使用StringBuffer类的substring()方法获取字符串部分内容的子串在Java编程中,经常需要对字符串进行处理和操作。StringBuffer类是一个常用的字符串类,它提供了一系列方便的方法来操作字符串。其中,substring()方法是一个非常常用的方法,可以用来获取字符串中的一部分内容,即子串。下面将介绍如何使用StringBuffer类的

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),