[D1,static array] fill static multidimensional array.

%u e at ee.com
Thu Oct 21 20:42:56 PDT 2010


== Quote from bearophile (bearophileHUGS at lycos.com)'s article
> %u:
> > What is the fastest way to fill a static multidimensional array?
> If you want a safe solution, then you probably need nested loops, and a array[]
= x; in the inner loop (such loops may be generated with a string mixin too).
> Otherwise if speed is more important, fixed sized multidimensional arrays are
stored in a contiguous way in D, so you may use a memset or something like:
> import std.stdio: writeln;
> void main() {
>     int[5][4] mat;
>     (cast(int[mat[0].length * mat.length])mat)[] = 10;
>     writeln(mat);
> }
> Or even:
> (cast(int[mat.sizeof / int.sizeof])mat)[] = 10;
> (If necessary you may use a recursive template trick to find the type of the
basic item of the array).
> Bye,
> bearophile

The code below gave me these timings:

[x][y][z]   : 4569947344
[x][y][]    : 4149326308
cast(int[*]): 3843939416
cast(int[1]): 3978162888

Depending on the dimensions of the array, one consistently wins, but always with
an -I-wouldn't-bother- margin.
How would memset work?

dmd(1) -O -inline -release
----
import std.stdio;
import std.perf;

int[50][50][50] arr;

void main()
{
	auto timer = new HighPerformanceCounter;

	timer.start();
	for(int i = 0; i < 10_000; i++) {
		for(int x = 0; x < 50; x++)
			for(int y = 0; y < 50; y++)
				for(int z = 0; z < 50; z++)
					arr[x][y][z] = i;
	}
	timer.stop();
	writefln("[x][y][z]   : ",timer.periodCount());

	timer.start();
	for(int i = 0; i < 10_000; i++) {
		for(int x = 0; x < 50; x++)
			for(int y = 0; y < 50; y++)
				arr[x][y][] = i;
	}
	timer.stop();
	writefln("[x][y][]    : ",timer.periodCount());

	timer.start();
	for(int i = 0; i < 10_000; i++) {
		(cast(int[arr[0][0].length * arr[0].length * arr.length])arr)[] = i;
	}
	timer.stop();
	writefln("cast(int[*]): ",timer.periodCount());

	timer.start();
	for(int i = 0; i < 10_000; i++) {
		(cast(int[125_000])arr)[] = i;
	}
	timer.stop();
	writefln("cast(int[1]): ",timer.periodCount());
}


More information about the Digitalmars-d-learn mailing list