Often repeated array allocations
Dmitry Olshansky
dmitry.olsh at gmail.com
Sun Jul 21 06:29:45 PDT 2013
21-Jul-2013 00:46, Namespace пишет:
> On Saturday, 20 July 2013 at 20:22:56 UTC, Dmitry Olshansky wrote:
>> 21-Jul-2013 00:19, Namespace пишет:
>>> Let us assume we have a method of a class which is used often and the
>>> method is called periodically and must allocate every time a array
>>> between 100 and 4000 elements. What would you do?
>>>
>>> 1. Simple: float[] array;
>>> 2. Reserve: float[] array; array.reserve(N); /// N is a parameter value
>>> 3. Use manual memory allocation (e.g. with malloc) and free the memory
>>> immediately at the end of the scope.
>>> 4. Use stack allocated memory (But maybe 4000 is too big?)
>>>
>>> Currently I would prefer #3, the manual memory allocation because I can
>>> then control when _exactly_ the memory is released. But I want to hear
>>> other opinions. :)
>>
>> 5. Keep a TLS scratch pad buffer (static class member) for said
>> 100-4000 floats and re-use it.
>
> TLS scratch pad buffer?
My analogy goes as follows: a chunk of memory for temporary needs =>
scratch pad (as in sheet of paper for quick notes/sketches).
Something along the lines of:
class A{
static float[] buffer;
static this(){
buffer = new float[as_big_as_it_gets];
}
void foo(){
float[] tempAlloc = buffer[0..need_this_much];
tempAlloc[] = 0.0;
...
}
}
As long as foo is not called recursively should just work. Other thing
that may wreck this is if foo is called in Fiber context and uses yeild
internally.
One may as well fall back to option 3 in rare cases where scratch pad is
too small to fit the bill.
--
Dmitry Olshansky
More information about the Digitalmars-d-learn
mailing list