Interesting Memory Optimization

Xinok xinok at live.com
Fri Mar 16 11:52:50 PDT 2012


On Friday, 16 March 2012 at 18:44:53 UTC, Xinok wrote:
> On Friday, 16 March 2012 at 15:41:32 UTC, Timon Gehr wrote:
>> On 03/16/2012 03:28 PM, H. S. Teoh wrote:
>>> More to the point, does dmd perform this optimization 
>>> currently?
>>>
>>>
>>> T
>>>
>>
>> No.
>>
>> immutable string a = "123";
>> immutable string b = a;
>>
>> void main(){writeln(a.ptr is b.ptr);} // "false"
>
> It actually does, but only identical strings. It doesn't seem 
> to do strings within strings.
>
> void foo(string a){
> 	string b = "123";
> 	writeln(a is b);
> }
>
> void main(){
> 	string a = "123";
> 	string b = "456";
> 	string c = "123456";
> 	foo(a);
> 	foo(b);
> 	foo(c);
> }
>
> Prints:
> true
> false
> false

Captain obvious to the rescue, 'is' is false if the strings are 
of different lengths >.<. But it still stands, D doesn't dedup 
strings within strings.

void main(){
	string a = "123";
	string b = "123456";
	writeln(a.ptr);
	writeln(b.ptr);
	writeln(a.ptr);
	writeln(b.ptr);
}

Prints:
44F080
44F090
44F080
44F090

I printed it twice to ensure it wasn't duping the strings.


More information about the Digitalmars-d mailing list