using D without GC
Oleg B via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun Jun 7 09:25:27 PDT 2015
> No just reserve some memory and preallocate the buffer you want
> before using it. It'll be a lot faster and cheaper.
I know, it's only for test.
> You shouldn't be using delete or new for that matter.
> You should be using malloc + free. And emplace.
auto myalloc(T)( size_t count )
{
struct Impl{ size_t len; void* ptr; }
union Wrap { Impl impl; T[] arr; }
auto ret = Wrap( Impl( count, calloc( count, T.sizeof ) )
).arr;
enforce( ret.ptr !is null );
return ret;
}
class Bar
{
float[] buf;
this() { buf = myalloc!float( 65536 ); }
~this() { free(buf.ptr); }
}
For simple types arrays all clear. Emplace realization not
trivial for me yet. As I understand correctly it concerns placing
initial values of struct for example or values before calling
ctor in place to array segment without copying?
But what I need use for class objects?
class Foo
{
Bar[] buf;
this()
{
buf = myalloc!Bar( 100 ); // I think it's ok
foreach( ref b; buf )
b = new Bar; // but calloc can't initialize class
correctly
}
~this()
{
static if( gc_disable )
{
foreach( ref b; buf ) delete b;
free(buf.ptr);
}
}
}
Operator new automatically allocate range in GC-manage memory? If
it is whether is possible to change this behavior? It's question
relates to emplace too?
More information about the Digitalmars-d-learn
mailing list