StringBuilder

From Helpful
Jump to navigation Jump to search
This article/section is a stub — probably a pile of half-sorted notes and is probably a first version, is not well-checked, so may have incorrect bits. (Feel free to ignore, or tell me)

OO languages that have immutable strings may have something like StringBuilder - a utility (class) that constructs a single string from many fragments of strings.


...because the naive way of doing that is a concatentation like "a"+"b"+"c"+"d"+'e"+"f"

since many string operations are a boolean operation, every concatenating immutable strings creates a new string object.
so you createa bunch of temporary objects to be created in memory, almost all of which could be immediately removed.


This results in more memory overhead than necessary (potentially on the order of eventual_length**2), and more CPU overhead.

If your plan was always 'join list into single thing', then StringBuilder is the thing that lets you collect the parts, and then join them once.


That said, StringBuilder is also sometimes overstated. When concatenating together just a handful of literals or variables, and it's not in an inner loop, there is often no discernible difference, and StringBuilder may sometimes even be more wasteful (there is often a bunch of bookkeeping. Also, sometimes the JIT compiler is smart enough to optimize especially the few-literal case, and that can't apply to StringBuilders), so in general, this may be micro-optimization and you don't really need to worry about.


Factors include:

  • the amount of strings/concatenations
  • size of the eventual string
  • your instantiation/use
  • The amount of work the compiler/interpreter has to do with a StringBuilder that it doesn't for a basic string.
  • StringBuilder's implementation
  • whether you can then use the StringBuffer itself, or have to create a new immutable String from it again
  • The cases that the code has to handle (joining two arguments? Joining an arbitrarily-sized list of strings)


Note that in your language there may be cases where a third option is better. For example, joining a list of strings into a new basic string may well be a an optimized case, certainly more efficient than piece-wise joining, but possibly also better than StringBuilder.