About this fast / best memory:
I reviewed this issue with Java, I believe .NET will be just as smart.
The implementation for String is pretty impressive.
The String object keeps track of “length” and “common” (regardless of the length of the array that contains the string)
So something like
String a = "abc" + "def" + "ghi";
can be implemented (by compiler / runtime) as:
- Extend the array holding "abc" by 6 additional spaces.
- Copy def in right after abc
- copy ghi in after def.
- give a pointer to the "abc" string to a
- leave abc length at 3, set a length to 9
- set the shared flag in both.
Since most lines are short-lived, in many cases this makes some VERY efficient code. The case when it is absolutely NOT effective when you add a line in a loop or when your code looks like this:
a = "abc"; a = a + "def"; a += "ghi";
In this case, you are much better off using the StringBuilder construct.
My point is that you should be careful when optimizing, unless you ALLOW that you know what you are doing, and you are absolutely sure that it is necessary. And you check that the optimized code makes a pass, just copy it in the most readable way and do not try to invent a compiler.
I spent 3 days using strings, caching / reusing string collectors and testing speed, before I looked at the source code of the string and realized that the compiler was already doing it better than I could for my use case. Then I had to explain how I did NOT REALLY know what I was doing, I thought I did ...
Bill K Oct 22 '08 at 22:46 2008-10-22 22:46
source share