StructType.init and StructType() cause a allocation
Benjamin Thaut
code at benjamin-thaut.de
Sat Jun 30 03:01:17 PDT 2012
If T is a struct both of the following statements will lead to a call of
the _d_arrayliteral function which will allocate a array of the size of
the struct just to initialize it!!
void T[] data = ...;
data[0] = T.init;
data[0] = T();
This has proven to be the biggest performance bottleneck in my current
codebase, replacing this statement with a unneccessary workaround speeds
my code up by factor 100. This is the cause because all of my container
classes tend to reinitialize the contents of the data arrays they are
holding. Also this bug makes it very hard to write non leaking code when
not using a GC. The replacement code could be
T temp;
data[0] = temp;
Which works correctly as long as T is publicly accessible, if it is a
private type this will not compile. Then you have to do some more fancy
stuff like:
void[T.sizeof] temp;
void[] initMem = typeid(T).init();
if(initMem.ptr is null)
memset(temp.ptr, 0, temp.length);
else
temp[] = initMem[];
data[0] = *cast(T*)temp.ptr;
How hard would it be to fix this?
It is really a shame that reinitalizing a struct
a) is a major performance bottleneck
b) leaks memory
I created a bug ticket for this 6 months ago, but it has been ignored so
far: http://d.puremagic.com/issues/show_bug.cgi?id=7271
Kind Regards
Benjamin Thaut
More information about the Digitalmars-d
mailing list