Interesting Memory Optimization
Timon Gehr
timon.gehr at gmx.ch
Fri Mar 16 11:55:59 PDT 2012
On 03/16/2012 07:52 PM, Xinok wrote:
> 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.
It can't because there must be a terminating zero byte. It does not do
it even if it could though.
immutable string x = "123";
immutable string y = "123";
void foo(string a){
string b = "123";
writeln(a is b);
}
void main(){
string a = "123";
string b = "456";
string c = "456123";
foo(c[3..$]); // false
writeln(x is y); // false
writeln(a is x); // false
writeln(b is x); // false
writeln(a is y); // false
writeln(b is y); // false
foo(a); // true
foo(b); // false
}
More information about the Digitalmars-d
mailing list