equivalent of python join?
Ali Çehreli
acehreli at yahoo.com
Tue Dec 3 00:19:45 PST 2013
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
> [2] http://dlang.org/phobos/std_array.html#.join
> [3] http://dlang.org/phobos/std_array.html#.Appender
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
More information about the Digitalmars-d-learn
mailing list