www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - equivalent of python join?

reply "CJS" <Prometheus85 hotmail.com> writes:
In python a common performance tip for joining many strings 
together is to use the join method. So, for example, instead of
"a" + "b" + "c"
use
''.join(["a","b","c"]).
The idea is to avoid creating temporary objects that are 
immediately thrown away. It's obviously overkill for such a small 
number of strings, though.

Is there any equivalent method/advice when concatenating many 
strings together in D?
Dec 02 2013
parent reply Jacob Carlborg <doob me.com> writes:
On 2013-12-03 07:36, CJS wrote:
 In python a common performance tip for joining many strings together is
 to use the join method. So, for example, instead of
 "a" + "b" + "c"
 use
 ''.join(["a","b","c"]).
 The idea is to avoid creating temporary objects that are immediately
 thrown away. It's obviously overkill for such a small number of strings,
 though.

 Is there any equivalent method/advice when concatenating many strings
 together in D?
There's std.algorithm.joiner[1] and std.array.join[2]. I don't know if they're any more efficient than using "~". There's also std.array.Appender[3] if you want to do a lot of appending and want the most efficient way. [1] http://dlang.org/phobos/std_algorithm.html#joiner -- /Jacob Carlborg
Dec 02 2013
parent =?UTF-8?B?QWxpIMOHZWhyZWxp?= <acehreli yahoo.com> writes:
On 12/02/2013 11:32 PM, Jacob Carlborg wrote:

 On 2013-12-03 07:36, CJS wrote:
 In python a common performance tip for joining many strings together is
 to use the join method. So, for example, instead of
 "a" + "b" + "c"
 use
 ''.join(["a","b","c"]).
 The idea is to avoid creating temporary objects that are immediately
 thrown away. It's obviously overkill for such a small number of strings,
 though.

 Is there any equivalent method/advice when concatenating many strings
 together in D?
There's std.algorithm.joiner[1] and std.array.join[2]. I don't know if they're any more efficient than using "~".
They are more efficient in the sense that they are lazy.
 There's also
 std.array.Appender[3] if you want to do a lot of appending and want the
 most efficient way.

 [1] http://dlang.org/phobos/std_algorithm.html#joiner


There is also the more general std.range.chain. It can join any type of range as long as the element types are the same: import std.stdio; import std.range; import std.algorithm; void main() { auto a_lazy_range_of_ints = chain(5.iota, [ 10, 9, 20, 8 ].filter!(a => a < 10)); // writeln consumes the range eagerly writeln(a_lazy_range_of_ints); // Prints [0, 1, 2, 3, 4, 9, 8] } Ali
Dec 03 2013