Memory allocation in D

Marius Muja mariusm at cs.ubc.ca
Wed Nov 28 16:57:32 PST 2007


Hi,

I'm working on a program that is computationally and memory intensive. I 
have noticed that if I allocate the memory using D's new operator I can 
allocate only about half as much memory compared to C's malloc (and also 
the memory allocation is much slower). Does anybody know why D's memory 
allocator uses twice as much memory compared to malloc?

I used the following test program to test this:

version (Tango){
import tango.core.Memory;
import tango.stdc.stdlib;
import tango.io.Stdout;
}
else
{
import std.stdio;
import std.c.stdlib;
}

const int ALLOC_SIZE = 1024*1024;

void test_d_alloc()
{
	float[] a = new float[ALLOC_SIZE];
}

void test_malloc()
{
	float* ptr = cast(float*)malloc(ALLOC_SIZE*float.sizeof);
	if (ptr is null) throw new Exception("Out of memory");
}

void main()
{
	version (Tango) {
		GC.disable();
	} else {
		std.gc.disable();
	}
	int i=0;
	while(true) {
		version (Tango) {
			Stdout.formatln("{}",++i);
		} else {
			writefln(++i);
		}
// 		test_d_alloc();
		test_malloc();
	}
}


When the above program uses the test_d_alloc() function it executes the 
loop about half as many times compared to when it's using the 
test_malloc() function (until it terminates with an out of memory 
error). Also when the allocation is done in smaller increments 
(ALLOC_SIZE is smaller) the test_d_alloc() version segfaults after 
allocating the maximum amount of memory (3G) instead of terminating with 
a nice OutOfMemory error.

Marius



More information about the Digitalmars-d mailing list