[Issue 17881] Provide mechanism to preallocate memory from the GC

d-bugmail at puremagic.com d-bugmail at puremagic.com
Wed Oct 11 20:26:55 UTC 2017


https://issues.dlang.org/show_bug.cgi?id=17881

--- Comment #9 from safety0ff.bugz <safety0ff.bugz at gmail.com> ---
(In reply to Steven Schveighoffer from comment #8)
> Internally, I think something like this is needed. What I am looking for,
> though, is the high-level API of "I have 20 million T's I want to allocate,
> give me them properly allocated and typed one at a time". I don't
> necessarily even think you need the TypeInfo for the low level API. Perhaps
> the bit attributes can even be done as you allocate each block.

Here's the rough sketch of one idea:

void[] gc_nmalloc(size_t num, size_t size, void[] prev = [], uint ba = 0, const
TypeInfo ti = null)
// prev is used for temporary pinning/unpinning a memory range

struct GC // in core.memory
{
  auto NMalloc(T)(size_t num) { // convenience function
     int loop(int delegate(T*) dg) {
       void[] prev; size_t remain = num;
       scope(exit) gc_nmalloc(0,T.sizeof,prev); // unpin last chunk
       int result;
       while (remain) {
         prev = gc_nmalloc(remain, T.sizeof, prev, ...);
         auto chunk = cast(T*)prev.ptr[0 .. prev.length/T.sizeof];
         foreach (ref e; chunk)
           if ((result = dg(&e))) return result;
         remain -= chunk.length;
       }
       return result;
     }
     return &loop;
  }
}

So user code could look like:
foreach (e; GC.NMalloc(T)(20_000_000))
    // do something with allocated e

--


More information about the Digitalmars-d-bugs mailing list