"immutable string" vs "const string*"

Dennis dkorpel at gmail.com
Sun Sep 9 11:01:33 UTC 2018


On Sunday, 9 September 2018 at 08:41:37 UTC, Christian Mayer 
wrote:
> As of my current understanding "char" will create a new 
> variable and copy the content of the original to the new 
> variable. "char*" will just use the pointer. And "const char*" 
> is good for when not modifying. But I also can achieve the same 
> using "immutable char".

In D, a string looks like this:
```
struct string {
   size_t length; // length of a string
   immutable(char)* ptr; // pointer to the actual characters of 
the string
}
```
On 32-bit, that struct has a size of 2*4 = 8 bytes. On 64-bit, 
it's 2*8 = 16 bytes.
So when you have a string in a function signature:
```
void print(string str);
```
In terms of performance and calling convention, that's basically 
the same as doing this in C:
```
void print(size_t length, char *string);
```
Except that in C, the length of strings is traditionally 
calculated based on the null-terminator instead of passed as 
parameter. In both cases, 8 (or 16 on 64-bit) bytes are passed to 
the function. When you use a string*, you give a pointer to a 
structure with a pointer and a length. This cuts the size of the 
function parameters in half (only 4 or 8 bytes are passed), but 
it adds an extra level of indirection. So it takes an extra 
instruction to dereference the pointer, makes it more error-prone 
for the programmer, and harder to reason about for the optimizer.

I'd recommend just passing strings as if they were a basic type, 
see [1].
As for when to use const and immutable, I recommend reading [2].

[1] https://digitalmars.com/articles/b01.html
[2] https://dlang.org/articles/const-faq.html


More information about the Digitalmars-d-learn mailing list