How to work with hashmap from memutils properly?

Siarhei Siamashka siarhei.siamashka at gmail.com
Fri Feb 11 02:43:24 UTC 2022


On Thursday, 10 February 2022 at 20:39:45 UTC, Sergey wrote:

> Code could be found here: 
> https://github.com/cyrusmsk/lang_benchmark/tree/main/lru/source/d_comparison/mem

Is this an attempt to implement a high performance solution for 
the Benchmarks Game's LRU problem in D language?

> PS it seems that almost all realisations of hashmap/dict/AA in 
> D very slow :(

Looks like your code that you are bolting on top of 
hashmap/dict/AA is very slow. Some major improvements are 
possible.

Though this strange benchmark is testing performance of an LRU 
with ... wait for it ... 10 elements, which makes using 
hashmap/dict/AA a completely ridiculous idea. You can try to test 
this code as a replacement for your LRU class:

```D
struct LRU(KT, VT)
{
     private int _size;
     private Tuple!(KT, VT)[] a;

     this(int size)
     {
         _size = size;
     }

     protected Tuple!(bool, VT) get(KT key)
     {
         foreach (i ; 0 .. a.length)
         {
             if (a[i][0] == key)
             {
                 auto tmp = a[i];
                 foreach (j ; i + 1 .. a.length)
                     a[j - 1] = a[j];
                 a.back = tmp;
                 return tuple(true, a.back[1]);
             }
         }
         return tuple(false, cast(VT) 0);
     }

     protected void put(KT key, VT value)
     {
         foreach (i ; 0 .. a.length)
         {
             if (a[i][0] == key)
             {
                 foreach (j ; i + 1 .. a.length)
                     a[j - 1] = a[j];
                 a.back = tuple(key, value);
                 return;
             }
         }
         if (a.length < _size)
         {
             a ~= tuple(key, value);
             return;
         }
         // FIXME: use ring buffer and this copy loop won't be 
necessary
         foreach (j ; 1 .. a.length)
             a[j - 1] = a[j];
         a.back = tuple(key, value);
     }
}
```
It can be further tuned for better performance if necessary.


More information about the Digitalmars-d-learn mailing list