Tips and Tricks for D

Deewiant deewiant.doesnotlike.spam at gmail.com
Mon Jul 3 01:15:09 PDT 2006


mclysenk at mtu.edu wrote:
> You can read it at http://www.assertfalse.com/articles/tricks.shtml .
> 
> Any comments, questions, suggestions or other feedback is welcome!
> 

I've always removed items from an array whilst preserving order in the following
way (using variables from your example):

queue = queue[0..idx] ~ queue[idx+1..$];

I did some test runs (benchmark source can be found at bottom of message), and
on my machine, at least, my version is consistently faster - it runs in about
60% of the time yours takes.

BTW, you write "tmp[].dup", which seems strange at least to my eyes: why not
just "tmp.dup"? It confused me for a moment, I wondered whether it was doing
something more than just a normal .dup operation.

All in all, yours is a fine article about D. I'm not sure I knew about slicing
pointers either. <g>

My benchmark code:

import std.stdio, std.perf;

void main() {
	const int REPEATS = 1000,
	          LENGTH  = 100000;

	const int[] removeThese = [0, 42, 999, 7, 1000, 6888, 999, 9992];
	int[] array;
	TickCounter t = new TickCounter();

	t.start;
	for (int i = 0; i < REPEATS; ++i) {
		array.length = LENGTH;

		foreach (n; removeThese) {
			if (n != array.length - 1) {
				int[] tmp = array[n+1..$];
				array[n..$-1] = tmp[].dup;
			}
			array.length = array.length - 1;
		}
	}
	t.stop;

	uint mTime = t.milliseconds;
	writefln("MLysenko: %6d ms for %6d repeats on %6d-length arrays (%.2f ms per
removal)", mTime, REPEATS, LENGTH, cast(real)mTime / REPEATS);

	t.start;
	for (int i = 0; i < REPEATS; ++i) {
		array.length = LENGTH;

		foreach (n; removeThese)
			array = array[0..n] ~ array[n+1..$];
	}
	t.stop;

	uint dTime = t.milliseconds;
	writefln("Deewiant: %6d ms for %6d repeats on %6d-length arrays (%.2f ms per
removal)", dTime, REPEATS, LENGTH, cast(real)dTime / REPEATS);
	
	writefln("D / M: %.2f", cast(real)dTime / mTime);
	writefln("M / D: %.2f", cast(real)mTime / dTime);
}



More information about the Digitalmars-d-learn mailing list