On Saturday, 23 March 2013 at 12:37:04 UTC, bearophile wrote:

Call assumeSafeAppend every time you want to append with no reallocations.

Thank you for the suggestion! This seems to work fast enough and never relocate:

-----
import core.memory;
import std.range;
import std.stdio;

void main ()
{
        version (NOGC) {GC.disable ();}
        int n = 1_000_000;
        auto s = array (iota (n));
        s.reserve (n * 2);
        foreach (i; 0..n)
        {
                assumeSafeAppend (s);
                debug {writefln ("before ++: %s %s", s.capacity, &s[0]);}
                s.length++;
                debug {writefln ("after ++: %s %s", s.capacity, &s[0]);}
                s.length--;
                debug {writefln ("after --: %s %s", s.capacity, &s[0]);}
        }
}
-----

Still, I am missing something here. After assumeSafeAppend(s), the capacity of s is restored to the original value (in my case, 2_000_891). That means the memory manager keeps track of the original array (memory, not view) and knows its limits. Can't it, or the compiler, also know there are no more writable views into that portion of memory and just optimize out the "capacity = 0" part? Does it lack such information, or is it hard to account for all possible scenarios? Or is "capacity = 0" actually useful for some other concern?

-----
Ivan Kazmenko.

Reply via email to