Search code examples
fantom

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


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.


Solution

  • 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.