Re: [PATCH 1/4] stringbuf: A string buffer implementation

Matt Mackall
2007-10-29T03:04:38Z

On Sat, Oct 27, 2007 at 08:09:30PM +1000, Rusty Russell wrote:
> On Saturday 27 October 2007 06:57:14 Matt Mackall wrote:
> > Well I expect once you start letting people easily build strings by
> > concatenation, you'll very shortly afterwards have people using them
> > in loops. And having hidden O(n^2) behavior in there is a little sad,
> > even though n will tend to be small and well-bounded. If we can do
> > something simple to avoid it, we should.
>
> Hi Matt,
>
> I avoid typing even a single character of optimization until it's
> justified. This is partially a reaction against the machoptimization
> tendencies of many kernel programmers, but it's mainly a concern at the
> kernel's complexity creep.
>
> Meanwhile, of course, I've now spent far too long analyzing this :)
>
> Building a 1000 byte string 1 byte at a time involves 6 reallocs (SLAB) or 10
> reallocs (SLUB). Frankly, that's good enough without an explicit alloc
> length field (better in some ways).

And on SLOB, which doesn't have those bloaty power-of-2 constraints?
Looks like ~500 reallocs, including 250000 bytes of memcpy. Ouch!

SLAB and SLUB (accidentally) internalize the optimization that I'm
proposing: grow the string by a constant factor at each step. Failing
to do that makes the behavior dismal.

--
Mathematics is the supreme nostalgia of our time.