string manipulation performance
Steven Schveighoffer
schveiguy at yahoo.com
Sun Jun 12 19:01:15 PDT 2011
On Sun, 12 Jun 2011 21:02:05 -0400, Lloyd Dupont <ld-REMOVE at galador.net>
wrote:
> But... string being immutable I don't see the point of allocating some
> space for one..
> Am I missing something?
Reserving space for appending does not make that space immutable, yet.
As far as the runtime is concerned, that space is unallocated. Although
it can only ever be allocated to have immutable string data, it's not
allocated yet, so it can be modified in the future.
Observe:
string s;
assert(s.ptr is null); // string is unallocated
s.reserve(100);
assert(s.length == 0); // reserve doesn't alter the actual string, it just
sets up space for it to grow into
assert(s.ptr !is null); // but now it points to a memory block!
auto sptr = s.ptr; // save pointer for later proof...
for(i; 0..20) s ~= "hello"; // make a bunch of hellos
assert(s.length == 100); // yep, we added some data, but
assert(s.ptr is sptr); // it didn't move, so essentially, it "grew" into
the existing memory block, that was previously unused.
The reason it works is because the unused space in the block has no
references, therefore, even though it is potentially immutable, it doesn't
matter that we change it because nobody else knows about it yet.
Note that without the reserve call, s.ptr would not be equal to sptr at
the end of the operation, because the runtime would have chosen smaller
memory blocks to begin with to store the string.
-Steve
More information about the Digitalmars-d-learn
mailing list