字符串vs StringBuffer vs StringBuilder

String is one of the most widely used classes in Java. StringBuffer and StringBuilder classes provide methods to manipulate strings. We will look into the difference between StringBuffer and StringBuilder. StringBuffer vs StringBuilder is a popular Java interview question.

字符串是Java中使用最广泛的类之一。 StringBuffer和StringBuilder类提供了操作字符串的方法。 我们将研究StringBuffer和StringBuilder之间的区别。 StringBuffer vs StringBuilder是一个受欢迎的Java面试问题。

字符串vs StringBuffer vs StringBuilder (String vs StringBuffer vs StringBuilder)

The string is one of the most important topics in the core java interview. If you are writing a program that prints something on the console, you are use String.

字符串是Java核心访谈中最重要的主题之一。 如果要编写在控制台上打印某些内容的程序,则使用String。

This tutorial is aimed to focus on major features of String class. Then we will compare the StringBuffer and StringBuilder classes.

本教程的重点是String类的主要功能。 然后,我们将比较StringBuffer和StringBuilder类。

Java中的字符串 (String in Java)

  1. String class represents character strings, we can instantiate String in two ways.
    String str = "ABC";
    // or 
    String str = new String("ABC");

    String类代表字符串,我们可以通过两种方式实例化String。
  2. String is immutable in Java. So it’s suitable to use in a multi-threaded environment. We can share it across functions because there is no concern of data inconsistency.

    字符串在Java中是不可变的。 因此,它适合在多线程环境中使用。 我们可以跨功能共享它,因为不必担心数据不一致。
  3. When we create a String using double quotes, JVM first looks for the String with the same value in the string pool. If found, it returns the reference of the string object from the pool. Otherwise, it creates the String object in the String pool and returns the reference. JVM saves a lot of memory by using the same String in different threads.

    当我们使用双引号创建String时,JVM首先在字符串池中查找具有相同值的String。 如果找到,它将从池中返回字符串对象的引用。 否则,它将在字符串池中创建String对象,并返回引用。 JVM通过在不同线程中使用相同的String来节省大量内存。
  4. If the new operator is used to create a string, it gets created in the heap memory.

    如果使用new运算符创建字符串,则会在堆内存中创建它。
  5. The + operator is overloaded for String. We can use it to concatenate two strings. Although internally it uses StringBuffer to perform this action.

    +运算符对于String重载。 我们可以使用它来连接两个字符串。 尽管在内部它使用StringBuffer执行此操作。
  6. String overrides equals() and hashCode() methods. Two Strings are equal only if they have the same character sequence. The equals() method is case sensitive. If you are looking for case insensitive checks, you should use equalsIgnoreCase() method.

    字符串覆盖equals()和hashCode()方法。 只有两个字符串具有相同的字符序列,它们才相等。 equals()方法区分大小写。 如果要查找不区分大小写的检查,则应使用equalsIgnoreCase()方法。
  7. The string uses UTF-16 encoding for the character stream.

    该字符串对字符流使用UTF-16编码。
  8. String is a final class. All the fields as final except “private int hash”. This field contains the hashCode() function value. The hashcode value is calculated only when the hashCode() method is called for the first time and then cached in this field. Furthermore, the hash is generated using the final fields of String class with some calculations. So every time the hashCode() method is called, it will result in the same output. For the caller, it seems like calculations are happening every time but internally it’s cached in the hash field.

    字符串是最后一堂课。 除“ private int hash”外,所有字段均为final。 该字段包含hashCode()函数值。 仅当首次调用hashCode()方法然后将其缓存在此字段中时,才计算哈希码值。 此外,使用String类的最终字段进行一些计算来生成哈希。 因此,每次调用hashCode()方法时,都会得到相同的输出。 对于调用者而言,似乎每次都在进行计算,但是内部将其缓存在哈希字段中。

字符串vs StringBuffer (String vs StringBuffer)

Since String is immutable in Java, whenever we do String manipulation like concatenation, substring, etc. it generates a new String and discards the older String for garbage collection.

由于String在Java中是不可变的,因此每当我们执行诸如串联,子字符串等之类的String操作时,它都会生成一个新的String并丢弃旧的String进行垃圾回收。

These are heavy operations and generate a lot of garbage in heap. So Java has provided StringBuffer and StringBuilder classes that should be used for String manipulation.

这些是繁重的操作,并在堆中生成大量垃圾。 因此,Java提供了应该用于String操作的StringBuffer和StringBuilder类。

StringBuffer and StringBuilder are mutable objects in Java. They provide append(), insert(), delete(), and substring() methods for String manipulation.

StringBuffer和StringBuilder是Java中的可变对象。 它们提供String操作的append(),insert(),delete()和substring()方法。

StringBuffer与StringBuilder (StringBuffer vs StringBuilder)

StringBuffer was the only choice for String manipulation until Java 1.4. But, it has one disadvantage that all of its public methods are synchronized. StringBuffer provides Thread safety but at a performance cost.

在Java 1.4之前,StringBuffer是String操作的唯一选择。 但是,其所有公共方法都是同步的,这是一个缺点。 StringBuffer提供线程安全性,但会降低性能。

In most of the scenarios, we don’t use String in a multithreaded environment. So Java 1.5 introduced a new class StringBuilder, which is similar to StringBuffer except for thread-safety and synchronization.

在大多数情况下,我们不在多线程环境中使用String。 因此,Java 1.5引入了一个新的StringBuilder类,该类与StringBuffer相似,除了线程安全性和同步性。

StringBuffer has some extra methods such as substring, length, capacity, trimToSize, etc. However, these are not required since you have all these present in String too. That’s why these methods were never implemented in the StringBuilder class.

StringBuffer具有一些额外的方法,例如子字符串,长度,容量,trimToSize等。但是,由于在String中也存在所有这些方法,因此不需要这些方法。 这就是为什么在StringBuilder类中从未实现这些方法的原因。

StringBuffer was introduced in Java 1.0 whereas StringBuilder class was introduced in Java 1.5 after looking at shortcomings of StringBuffer.

在考虑了StringBuffer的缺点之后,在Java 1.0中引入了StringBuffer,而在Java 1.5中引入了StringBuilder类。

If you are in a single-threaded environment or don’t care about thread safety, you should use StringBuilder. Otherwise, use StringBuffer for thread-safe operations.

如果您在单线程环境中或不关心线程安全,则应使用StringBuilder。 否则,请使用StringBuffer进行线程安全操作。

StringBuilder vs StringBuffer性能 (StringBuilder vs StringBuffer Performance)

I am trying to check the effect on performance because of synchronization with a sample program that performs append() on StringBuffer and StringBuilder object for multiple times.

我试图检查对性能的影响,因为它与一个示例程序同步,该示例程序多次对StringBuffer和StringBuilder对象执行append()

package com.journaldev.java;

import java.util.GregorianCalendar;

public class TestString {

	public static void main(String[] args) {
		System.gc();
		long start=new GregorianCalendar().getTimeInMillis();
		long startMemory=Runtime.getRuntime().freeMemory();
		StringBuffer sb = new StringBuffer();
		//StringBuilder sb = new StringBuilder();
		for(int i = 0; i<10000000; i++){
			sb.append(":").append(i);
		}
		long end=new GregorianCalendar().getTimeInMillis();
		long endMemory=Runtime.getRuntime().freeMemory();
		System.out.println("Time Taken:"+(end-start));
		System.out.println("Memory used:"+(startMemory-endMemory));
	}
}

I ran the same code for the StringBuffer object also to check the time and memory values. I have executed the code 5 times for each case and then calculated the average values.

我为StringBuffer对象运行了相同的代码,还检查了时间和内存值。 我已经为每种情况执行了5次代码,然后计算了平均值。

Value of iStringBuffer (Time, Memory)StringBuilder (Time, Memory)
10,00,000808, 149356704633, 149356704
1,00,00,0007448, 1477838886179, 147783888
我的价值 StringBuffer(时间,内存) StringBuilder(时间,内存)
10,00,000 808,149356704 633,149356704
1,00,00,000 7448,147783888 6179,147783888

It’s clear that StringBuilder performs better than StringBuffer even in the case of a single-threaded environment. This difference in performance can be caused by synchronization in StringBuffer methods.

显然,即使在单线程环境中,StringBuilder的性能也比StringBuffer好。 性能上的这种差异可能是由StringBuffer方法中的同步引起的。

字符串vs StringBuffer vs StringBuilder (String vs StringBuffer vs StringBuilder)

  1. String is immutable whereas StringBuffer and StringBuilder are mutable classes.

    String是不可变的,而StringBuffer和StringBuilder是可变的类。
  2. StringBuffer is thread-safe and synchronized whereas StringBuilder is not. That’s why StringBuilder is faster than StringBuffer.

    StringBuffer是线程安全和同步的,而StringBuilder不是。 这就是StringBuilder比StringBuffer更快的原因。
  3. String concatenation operator (+) internally uses StringBuffer or StringBuilder class.

    字符串串联运算符(+)在内部使用StringBuffer或StringBuilder类。
  4. For String manipulations in a non-multi threaded environment, we should use StringBuilder else use StringBuffer class.

    对于非多线程环境中的String操作,应使用StringBuilder,否则应使用StringBuffer类。

That’s all for a quick roundup of difference between String, StringBuffer, and StringBuilder. StringBuilder is better suited than StringBuffer in most of the general programming scenarios.

这就是为了快速汇总String,StringBuffer和StringBuilder之间的差异。 在大多数常规编程方案中,StringBuilder比StringBuffer更适合。

References:

参考文献:

翻译自: https://www.journaldev.com/538/string-vs-stringbuffer-vs-stringbuilder

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值