On Sunday, 8 December 2013 at 09:25:41 UTC, Namespace wrote:
On Sunday, 8 December 2013 at 09:14:44 UTC, Dmitry Olshansky
wrote:
08-Dec-2013 02:32, Namespace пишет:
Since my last thread doesn't get much attention I like to ask
here: How
did you deal with temporary memory? Let's assume that the
size is only
known at runtime.
I have this situation e.g. in Dgame in the capture method: I
get the
pixel data from my Window with glReadPixel but it is
reversed. So I have
to reverse it again, but I still need at least temporary
memory for one
pixel-line which stores the currently swapped pixels. So how
would you
solve such a situation?
Since D doesn't offer VLA's and alloca is broken (besides the
ugly syntax),
I use a scoped wrapper (since scope doesn't do the job):
----
struct scoped(A : T[], T) {
T[] arr;
alias arr this;
this(T[] arr) {
this.arr = arr;
writefln("Get %d %s's (ptr = %x)", arr.length,
T.stringof,
arr.ptr);
}
~this() {
GC.free(this.arr.ptr);
this.arr = null;
GC.minimize();
This is slow. Just use malloc & free, why touch GC at all?
}
}
void main() {
// need temp memory
scoped!(int[]) arr = new int[n];
}
----
And what do you use?
Because it's more D'ish. That is what D offers.
Why is it slower than malloc + free?
Well, for a start you're calling GC.minimize every time you leave
the scope, which is an expensive call.
Just using new and GC.free would be fine, but there is really no
need to burden the GC with this at all; it's a textbook case for
C's malloc/free.