Samuel Hapak
Samuel Hapak

Reputation: 7192

Why to use StringBuffer in Dart instead of Iterable.join?

In Dart, you can concatenate Strings effectively by two ways: you can use StringBuffer class and then convert it to the String, or you can put all of your substrings into the List and then call join('') on them.

I do not understand, what are the pluses of the StringBuffer and why should I use it instead of joining List. Could someone please explain?

Upvotes: 12

Views: 6346

Answers (3)

Fox32
Fox32

Reputation: 13560

There isn't a big difference. If you already have a list of strings, there is no difference in using StringBuffer.writeAll or Iterable.join. The Iterable.join method uses a StringBuffer internaly:

String join([String separator = ""]) {
 StringBuffer buffer = StringBuffer();
 buffer.writeAll(this, separator);
 return buffer.toString();
}

From the Dart documentation.

Upvotes: 18

Gábor
Gábor

Reputation: 10254

Not a direct answer but it might still help some people (just like me who came here while trying to eke out the most from these builders). I saw rather significant speedups with custom built string buffers like these:

If you can afford an upper capacity limit (no range checking, add if needed):

class StringBuilder {
  List<int> str;
  int position = 0;

  StringBuilder(int capacity) {
    str = List<int>(capacity);
  }

  void clear() {
    position = 0;
  }

  @override
  String toString() => String.fromCharCodes(str, 0, position);

  void write(String s) {
    for (int ch in s.codeUnits) str[position++] = ch;
  }

  void writeCharCode(int ch) {
    str[position++] = ch;
  }
}

If you can't:

class StringBuilder {
  List<int> str;

  StringBuilder() {
    str = <int>[];
  }

  void clear() {
    str.clear();
  }

  @override
  String toString() => String.fromCharCodes(str);

  void write(String s) {
    str.addAll(s.codeUnits);
  }

  void writeCharCode(int ch) {
    str.add(ch);
  }
}

I used them in format converters that have to do quite a lot of string manipulation (think XML parsing and similar) and it really helps. It those cases, it gets called repeatedly tens or hundreds of thousand of times and I could reduce the whole parsing time to around half in a specific case.

Upvotes: 0

davemeetsworld
davemeetsworld

Reputation: 142

StringBuffer is more efficient as it doesn't create a string object until you call toString.

Seth Lad blogged about the benefits here with some numbers to back it up.

There is a similar blog post about this here.

Upvotes: 0

Related Questions