If you have been programming in Dart, you might have noticed String and StringBuffer classes. Both String and StringBuffer are there in Dart with different purposes.

How are they different?

A String is a collection of characters enclosed within single or double quotation marks, and it is immutable. In contrast, a StringBuffer is also a collection of characters enclosed within single or double quotation marks, but it is mutable.

Before diving into their performance differences, let's understand the concepts of mutable and immutable. Mutable refers to data that can be changed after creation, whereas immutable refers to data that cannot be changed after creation.

Whenever we perform various operations on the String class, a new object is created in memory each time, which consumes memory for every operation performed (due to immutability). This is not the case with StringBuffer; every time we perform various operations, the same object is modified instead.

None
Image credit

Let us understand the performance of both with the help of simple dart program.

void main() {
  String foo = "foo";
  Stopwatch stopwatch = Stopwatch()..start();
  for (int i = 0; i <= 200000; i++) {
    foo = foo + " ";
  }
  print("Total time taken by String class ${stopwatch.elapsed}");
}

Total time taken by String class 0:00:01.979840

void main() {
  StringBuffer foo = StringBuffer("foo");
  Stopwatch stopwatch = Stopwatch()..start();
  for (int i = 0; i <= 200000; i++) {
    foo.write(" ");
  }
  print("Total time taken by StringBuffer class ${stopwatch.elapsed}");
}

Total time taken by StringBuffer class 0:00:00.010722

The elapsed time of approximately 1.98 seconds for concatenating 200,000 spaces highlights the inefficiency of String for such tasks.

In summary, StringBuffer is more efficient for dynamic string manipulation tasks that involve frequent modifications, as it reduces memory usage and execution time compared to using the String class.