Fast GC allocation of many small objects

Rémy Mouëza remy.moueza-dontspamme at gmail.com
Sat Mar 31 17:41:35 UTC 2018


On Saturday, 31 March 2018 at 09:10:13 UTC, Boris-Barboris wrote:
> On Friday, 30 March 2018 at 20:31:35 UTC, Per Nordlöw wrote:
>> Is there a faster way of allocating many small class objects 
>> such as...
>
> maybe something like this:
>
> import std.conv: to;
> import std.stdio;
>
> class Node {}
>
> class StrNode : Node
> {
>     string value;
> }
>
> void main()
> {
>     writeln(StrNode.classinfo.name);	// onlineapp.StrNode
>     size_t il = StrNode.classinfo.m_init.length;
>     writeln(il); // 32
>     void[] backBuf = new void[il * 1000];
>     StrNode[] nodes = new StrNode[1000];
>     for (int i = 0; i < 1000; i++)
>     {
>         backBuf[i * il .. (i+1) * il] = 
> StrNode.classinfo.m_init;
>         nodes[i] = cast(StrNode) &backBuf[i * il];
>         nodes[i].value = i.to!string;
>     }
>     foreach (n; nodes[995..$])
>         writeln(n.classinfo.name, " ", n.value);	
>         // prints onlineapp.StrNode 995-999
> }

I would have used std.conv.emplace:

import std.stdio;
import std.conv : emplace, to;

class Node {
     string value;

     this (long n) {
         this.value = n.to!string;
     }

     override string toString () {
         return "Node (value: " ~ value ~ ")";
     }
}

void main (string [] args) {

     /* size_t size = Node.sizeof; */
     size_t size = Node.classinfo.m_init.length;
     void [] memory = new void [size * 1000];
     Node [] nodes  = new Node [1000];

     foreach (i, node; nodes) {
         void [] buf = memory [i * size.. i * size + size];
         nodes [i] = emplace!Node (buf, i);
     }
     nodes [0]  .writeln;
     nodes [$-1].writeln;
}



More information about the Digitalmars-d-learn mailing list