[webkit-dev] String::operator+= considered harmful

Adam Barth abarth at webkit.org
Tue Sep 4 16:22:27 PDT 2012


As part of the work to deploy efficient string patterns [1] throughout
WebKit, Benjamin and I noticed a bunch of very inefficient code that
uses operator+= with Strings:

String foo;
for (...)
  foo += [...];
return foo;

This pattern is particularly inefficient because += mallocs an
entirely new buffer for the result and copies the the string into the
new buffer.  That means that this pattern makes O(n) calls to malloc
and does O(n^2) work.  A more efficient pattern is to use
StringBuilder:

StringBuilder foo;
for (...)
  foo.append([...]);
return foo.toString();

I'm in the process of going through WebCore and removing all callers
of WTF::String::operator+=.  Once that's complete, my plan is to
remove WTF::String::operator+= from WTFString.h.  Hopefully that will
nudge contributors and reviewers towards more efficient string
patterns.

Removing operator+= will likely require changes to a number of
port-specific files.  I'll do my best to remove these, but I might
need some help from maintainers of individual ports.  If you're
interested in helping out, please let me know.

Many thanks,
Adam

[1] http://trac.webkit.org/wiki/EfficientStrings


More information about the webkit-dev mailing list