本文介绍了字符串、StringBuffer 和 StringBuilder的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请告诉我一个实时情况来比较StringStringBufferStringBuilder?

Please tell me a real time situation to compare String, StringBuffer, and StringBuilder?

推荐答案

可变性差异:

String不可变的,如果您尝试更改它们的值,则会创建另一个对象,而 StringBufferStringBuilder可变的,因此它们可以更改其值.

String is immutable, if you try to alter their values, another object gets created, whereas StringBuffer and StringBuilder are mutable so they can change their values.

线程安全差异:

StringBufferStringBuilder 的区别在于 StringBuffer 是线程安全的.因此,当应用程序只需要在单个线程中运行时,最好使用 StringBuilder.StringBuilderStringBuffer 效率更高.

The difference between StringBuffer and StringBuilder is that StringBuffer is thread-safe. So when the application needs to be run only in a single thread then it is better to use StringBuilder. StringBuilder is more efficient than StringBuffer.

情况:

  • 如果您的字符串不会改变,请使用 String 类,因为 String 对象是不可变的.
  • 如果您的字符串可以更改(例如:字符串构造中的大量逻辑和操作)并且只能从单个线程访问,则使用 StringBuilder 就足够了.
  • 如果您的字符串可以更改,并且可以从多个线程访问,请使用 StringBuffer,因为 StringBuffer 是同步的,因此您具有线程安全性.
  • If your string is not going to change use a String class because a String object is immutable.
  • If your string can change (example: lots of logic and operations in the construction of the string) and will only be accessed from a single thread, using a StringBuilder is good enough.
  • If your string can change, and will be accessed from multiple threads, use a StringBuffer because StringBuffer is synchronous so you have thread-safety.

这篇关于字符串、StringBuffer 和 StringBuilder的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 12:37