-1

Possible Duplicate:
String, StringBuffer, and StringBuilder

what is the difference (advantages, disadvantages) between using StringBuilder instead String

StringBuilder text = new StringBuilder();
String cadena = "";
Scanner scanner = new Scanner(new FileInputStream(fFileName), fEncoding);
try {
  while (scanner.hasNextLine()) {
    String line = scanner.nextLine();
    text.append(line);
    cadena += line;
  }
} finally {
  scanner.close();
}    
Community
  • 1
  • 1
rkmax
  • 17,633
  • 23
  • 91
  • 176

1 Answers1

3

It's faster, but isn't thread-safe.

You can build strings basically three ways.

  1. by just concatenating strings ("foo" + "bar") - slowest
  2. by using StringBuffer, which is thread-safe, and faster than #1
  3. by using StringBuilder, which is the fastest of all, but not thread-safe

Some other distinctions:

String: Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Concatenating strings using the + operator doesn't modify the Strings involved, it creates a new String that is a combination of the Strings you're concatenating.

StringBuffer: A thread-safe, mutable sequence of characters. A string buffer is like a String, but can be modified.

StringBuilder: A mutable sequence of characters. This class provides an API compatible with StringBuffer, but with no guarantee of synchronization.

jefflunt
  • 33,527
  • 7
  • 88
  • 126
  • 2
    ..plus, (1) will be creating a new instance of class String every time you do "+" since Strings are immutable. – mazaneicha Oct 07 '11 at 00:59
  • 1
    ...though given that the compiler will turn most string concatenation (including that above) into a StringBuilder, it's not worth the effort to even worry about it unless you have a profiler telling you there's a problem. – Ryan Stewart Oct 07 '11 at 01:37
  • Agreed. I hardly ever use anything but String concatenation, because that's never been the performance bottleneck in any app I've written, but that's technically the official answer. I'm not a fan of micro-optimizations without proof either. – jefflunt Oct 07 '11 at 01:46