My AoC program in D is just as fast as in Python

Paul Backus snarwin at gmail.com
Wed Nov 26 15:37:48 UTC 2025


On Monday, 24 November 2025 at 14:37:22 UTC, Jabba Laci wrote:
> Another question: for `process_line()`, I pass the dictioary by 
> reference, since I want to modify the dictionary inside this 
> procedure. Without `ref`, the original `d` in `main()` remained 
> empty. However, I've already written programs when I passed a 
> dictionary without `ref` and the changes to the dictionary were 
> visible outside of the procedure. What's the rule here?

When you declare an associative array (dictionary) variable in D, 
what's stored in the variable is a pointer. By default, that 
pointer is `null`. When you pass an AA to a function by value 
(without using `ref`), the function receives a copy of the 
pointer.

Normally, you might expect that attempting to insert a value into 
a `null` AA would result in an error or exception. However, the D 
runtime has a special feature to prevent this: when inserting a 
value into an AA, if the pointer to the AA is `null`, the runtime 
allocates a new AA automatically before performing the insertion, 
and updates the `null` pointer to point to it.

So what's happening is, you're passing a copy of your `null` AA 
pointer to your function, that function is allocating a new AA, 
and then when the function returns, your original pointer is 
still `null`.

The simplest way to work around this is to initialize your AA 
variable to a non-`null` value. For example:

```d
int[Pair] d = new int[Pair];
```


More information about the Digitalmars-d-learn mailing list