What's the best way to append a StrBuf to a StrBuf?

91 views Asked by At

I have a series of StrBuf objects and want to know the most efficient way to concatenate them together.

There's the add() method but the docs say, "Add x.toStr to the end of this buffer". If I'm doing this over and over and over again, I'd imagine that StrBuf.toStr() is not that performant.

(I know the real answer is to just use the one StrBuf, but humour me here!)

Cheers.

UPDATE:

Looking at the Java source, under the hood StrBuf uses a Java StringBuilder which uses a char array as it's internal buffer. So @Adrian, yeah, it's important to have a large initial buffer.

As far as StrBuf.toStr() is concerned, a new Java String is created using Arrays.copyOfRange() - which is reasonable but unnecessary given there's an append(StringBuffer sb) method.

2

There are 2 answers

2
afrankvt On BEST ANSWER

Not really - there are no optimizations in StrBuf for that case. You seeing performance issues with what you have today?

Generally for our APIs we would pass around the OutStream instance from StrBuf.out and not the actual StrBuf instance. Not sure if that helps your case or not.

1
Adrian Panasiuk On

I suppose you could create a new StrBuf with a big enough capacity:

capacity
    Int capacity
    The number of characters this buffer can hold without allocating more memory.

make
    new make(Int capacity := 16)
    Create with initial capacity (defaults to 16)