proposal: capacity variable for dynamic arrays
Ameer Armaly
ameer_armaly at hotmail.com
Mon Jul 10 09:22:30 PDT 2006
Right now dynamic arrays use length to resize and handle memmory allocation.
This is a bit limiting as far as the old memmory reservation problem as
well as a few other things. What I propose is adding a new variable called
capacity, which handles the actual memmory allocation and using length for
the accepted size of the array. Here are a few code fragments to show how
it would work:
char[] string = new char[1024];
assert(string.length==1024 && string.capacity=1024);
string.length=0; // we've reserved memmory, but haven't freed it
version(break) writefln(string[1..4]); // throws a bounds exception, since
length is zero
string.capacity = 1300; // traditional resize with a different variable,
will be set to whatever the true capacity is
string.length = 2048; // would still work, since length is greater than
capacity so it acts the same way. However, capacity would be the actual
amount of memmory reserved by the malloc algorithm, in this case doubling
the size of the array.
string.capacity = 0; // freed
In short, this solves the problem of reserving memmory with little cost,
while maintaining backwards compatibility. It could also be used in the
stream and socket code, where the actual capacity doesn't change but the
length does, removing the need for a separate size variable, something like
this:
char[] buf = new char[1024];
buf.length = 0;
Socket s;
// set up the socket
s.read(buf); // Length is set to the actual data, but capacity is the same.
This way the array is truely dynamic.
Thoughts?
--
Ameer
---
Life is either tragedy or comedy. Usually it's your choice. You can whine or
you can laugh.
--Animorphs
More information about the Digitalmars-d
mailing list