See sample code:
string x = "foobar";
string y;
y ~= x;
import std.stdio;
writefln("%x %x", x.ptr, y.ptr);
We can see here that a new allocation is done and the content of x copied in it. However, this reallocation is superfluous and a waste of perfectly good CPU cycles and memory :)
Comment #1 by b2.temp — 2021-09-03T17:32:18Z
added "backend tag" b/c the suggested optim is not portable (https://dlang.org/dmd-linux.html#differences), so it's eventually only possible in the backend and for windows. on linux your clearly see that the first address is within the mapping of the running executable and not on the heap.
Comment #2 by b2.temp — 2021-09-03T17:36:56Z
the runtime does know the platform but it does not know if it has to happen to a string literal.
Comment #3 by b2.temp — 2021-09-03T17:38:51Z
*append
Comment #4 by deadalnix — 2021-09-03T17:42:10Z
How is this relevent where the memory is located?
[] ~ x is x, no matter where x is located.
Comment #5 by b2.temp — 2021-09-03T18:00:51Z
sorry for some reasons I've read the report too fast (x ~= y) and runined it.
I suggest you to close this one and open the same report again.
Comment #6 by dlang-bugzilla — 2021-09-03T18:02:11Z
It would be a breaking change.
///////////// test.d /////////////
string fun() @safe
{
immutable char[3] arr = "foo";
string s = arr[];
string r;
r ~= s;
return r;
}
//////////////////////////////////
Comment #7 by deadalnix — 2021-09-03T23:44:43Z
(In reply to Vladimir Panteleev from comment #6)
> It would be a breaking change.
>
> ///////////// test.d /////////////
> string fun() @safe
> {
> immutable char[3] arr = "foo";
> string s = arr[];
> string r;
> r ~= s;
> return r;
> }
> //////////////////////////////////
I don't think this is a reasonable expectation that there is duplication here. If you want it heap allocated, you ought to call dup/idup.
After all, it does it the other way around:
> string fun(string stuff)
> {
> immutable char[3] arr = "foo";
> string s = arr[];
> return s ~ stuff;
> }
This is all good and well, until stuff is an empty array, in which case it is not anymore.
Comment #8 by robert.schadek — 2024-12-13T19:18:19Z