Dynamic array as stack and GC.BlkAttr.APPENDABLE

Steven Schveighoffer via Digitalmars-d digitalmars-d at puremagic.com
Fri Nov 14 14:38:53 PST 2014


On 11/14/14 5:25 PM, Dmitry Olshansky wrote:
> 15-Nov-2014 01:16, IgorStepanov пишет:
>> Recently I encountered the following problem.
>> I need a simple stack of uint.
>> I want to push uints back and pop it. I don't want to copy this stack
>> and I want it to work fast.
>>
>> In a first approximation, the problem seems easy.
>>
>> uint[] my_stack;
>> my_stack.reserve(256);
>>
>> my_stack ~= 1; //push
>> uint head = my_stack[$ - 1]; //top
>> my_stack.length--; //pop
>
> Just make push into:
>
> my_stack.assumeSafeAppend();
> my_stack ~= value;
>
> To avoid relocations.
>

In actuality, you do not need this before every push. You only need it 
between a pop and a push.

I highly recommend not doing arrays-as-stacks, because you end up 
writing your own type. At that point, you may as well remove the funky 
array/slice semantics, and store the capacity yourself.

-Steve


More information about the Digitalmars-d mailing list