Use case: eliminate hidden allocations in buildPath

Brad Anderson eco at gnuk.net
Thu Dec 5 12:58:31 PST 2013


On Thursday, 5 December 2013 at 17:30:37 UTC, inout wrote:
> My approach in cases like that used to be to pass an optional 
> char[] buffer = null as last argument (it doesn't work as nice 
> in variadic functions though):
>
> // constructs the result in a buffer if one is passed until 
> there is no more space left, in which case it reallocates the 
> buffer
> char[] buildPath(const(char)[] path1, const(char)[] path2, 
> char[] buffer = null) {
>   Appender!(char) appender = useBuffer(buffer);
>   ...
> }

The nice thing about output ranges instead of this approach is 
the allocation strategy is left up to the caller rather than the 
function.  I think generalized SSO (a small static buffer that 
can fall back to a dynamic allocation) will become a very common 
idiom as more and more of phobos accepts output ranges.


More information about the Digitalmars-d mailing list