Efficiency of using array as stack
Ali Çehreli
acehreli at yahoo.com
Sun Mar 24 09:41:29 PDT 2013
On 03/23/2013 03:28 PM, Ivan Kazmenko wrote:
> 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).
assumeSafeAppend allows the programmer to say "I am sure there is no
other reference to the rest of this slice."
> That means the memory manager keeps track of the original array (memory,
> not view) and knows its limits.
Yes.
> 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?
Such solutions would be too slow or consume too large memory. For each
slice to know about what other slices are doing, they would have to
reference some common information about how the elements in that region
of memory are being shared.
int[] makeArray()
{
auto result = new int[10];
// ...
return result;
}
void main()
{
auto a = makeArray();
auto b = a[0..$/2]; // first half
auto c = a[$/2..$]; // second half
--a.length; /* The runtime would have to somehow let 'c' know
* that 'c' can now safely append, while neither
* 'a' nor 'b' can do so. */
}
Quoting the array article, here is D's choice: "Remember, the slice
doesn't know what other slices refer to that data, or really where it is
in the array (it could be a segment at the beginning or the middle)."
http://dlang.org/d-array-article.html
Ali
More information about the Digitalmars-d-learn
mailing list