Appender is ... slow
Philippe Sigaud via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Aug 15 01:35:32 PDT 2014
> I wonder if using plain `Array` instead may be result in better performance
> where immutability is not needed.
Hmm, no:
module appendertest;
import std.array;
import std.datetime;
import std.stdio;
import std.container;
enum size = 1_000;
void test1()
{
auto arr = appender!(int[])();
foreach(n; 0 .. size)
arr.put(n);
}
void test1prime()
{
auto arr = appender!(int[])();
foreach(n; 0 .. size)
arr ~= n;
}
void test2()
{
int[] arr;
foreach(n; 0 .. size)
arr ~= n;
}
void test2prime()
{
int[] arr;
arr.reserve(size);
foreach(n; 0 .. size)
arr ~= n;
}
void test3()
{
Array!int arr;
foreach(n; 0 .. size)
arr ~= n;
}
void test3prime()
{
Array!int arr;
arr.reserve(size);
foreach(n; 0 .. size)
arr ~= n;
}
void test4()
{
auto arr = new int[](size);
foreach(n; 0 .. size)
arr[n] = n;
}
void test5()
{
auto arr = uninitializedArray!(int[])(size);
foreach(n; 0 .. size)
arr[n] = n;
}
void main()
{
auto result = benchmark!(test1, test1prime,
test2, test2prime,
test3, test3prime,
test4,
test5
)(10_000);
writeln("Appender.put :", cast(Duration)result[0]);
writeln("Appender ~= :", cast(Duration)result[1]);
writeln("Std array :", cast(Duration)result[2]);
writeln("Std array.reserve :", cast(Duration)result[3]);
writeln("Array :", cast(Duration)result[4]);
writeln("Array.reserve :", cast(Duration)result[5]);
writeln("new T[]() :", cast(Duration)result[6]);
writeln("uninitializedArray :", cast(Duration)result[7]);
}
Times:
Appender.put :157 ms, 602 μs, and 3 hnsecs
Appender ~= :182 ms, 807 μs, and 1 hnsec
Std array :256 ms, 210 μs, and 7 hnsecs
Std array.reserve :244 ms, 770 μs, and 4 hnsecs
Array :336 ms, 207 μs, and 3 hnsecs
Array.reserve :321 ms, 500 μs, and 6 hnsecs
new T[]() :28 ms, 496 μs, and 6 hnsecs
uninitializedArray :26 ms and 620 μs
More information about the Digitalmars-d-learn
mailing list