By ref and by pointer kills performance.

Richard (Rikki) Andrew Cattermole richard at cattermole.co.nz
Fri Feb 16 11:10:13 UTC 2024


On 16/02/2024 11:23 PM, Kagamin wrote:
> On Friday, 16 February 2024 at 09:56:50 UTC, Richard (Rikki) Andrew 
> Cattermole wrote:
>> That covers immutable, but not immutable that has become const.
> 
> That's fine, const can't be restrict qualified unconditionally, but 
> immutable can.
It is not fine.

Immutable objects can be in read only memory, since nothing is allowed 
to modify the contents process wide.

Write to it, and see how the program segfaults.

Just to prove a point of what immutable enables a compiler to do:

```d
import std.stdio;
import core.sys.posix.sys.mman;
import core.sys.posix.unistd : sysconf, _SC_PAGESIZE;
import core.sys.posix.stdlib;

void main() {
     auto pagesize = sysconf(_SC_PAGESIZE);
     int* temp;
     posix_memalign(cast(void**)&temp, pagesize, 4 * pagesize);
     data = temp[0 .. pagesize];

     data[0 .. 2] = [1, 2];
     mprotect(data.ptr, int.sizeof * data.length, PROT_READ);
     writeln(data[0 .. 2]);

     data[0 .. 2] = [3, 4];
     writeln(data[0 .. 2]);
}

static int[] data;
```

```
[1, 2]
Error: program killed by signal 11
```

Read only memory like this is useful to kernels, it enables them to map 
the same ram ranges to multiple processes.

It provides a very strong guarantee, well beyond const and right now 
that guarantee isn't honored in the language and needs to be fixed 
(otherwise why have it at all?).


More information about the Digitalmars-d mailing list