staticIndexOf is incredibly slow and memory intensive

Artur Skawina art.08.09 at gmail.com
Sun Aug 26 14:58:18 PDT 2012


On 08/26/12 23:03, Andrej Mitrovic wrote:
> Maybe this is CTFE to blame more than the function itself.
> 
> I have a project where I have a TypeTuple that holds a class tree of a
> wrapped C++ library. The tuple is iterated from in several places
> where an index has to be retrieved. Compiling this project takes 46
> seconds when using staticIndexOf and uses 700 MB RAM. If I replace it
> with my own hardcoded function below it takes only 5 seconds and uses
> 150 MB RAM. This is what the function looks like:
> 
> template myStaticIndexOf(T, TList...)
> {
>     static if (is(typeof(T == TList[0])) && is(T == TList[0]))
>         enum myStaticIndexOf = 0;
>     else
>     static if (is(typeof(T == TList[1])) && is(T == TList[1]))
>         enum myStaticIndexOf = 1;
>     else
>     // ... and so on ...
> }
> 
> The body is pregenerated of course, using mixin() would slow down
> compilation here as well.
> 
> When wrapping larger libraries (and hence having a larger TypeTuple)
> and using staticIndexOf the memory usage becomes so high that the
> compiler runs out of memory and crashes.
> 
> I really think it sucks that I have to resort to manually
> pre-generating a function body externally as if I were using a lame
> (CTFE-wise) language like C++03.
> 
> D *has* to be better than this..

   template staticIndexOf(T, TS...) {
      enum staticIndexOf = {
         foreach(size_t i, I; TS)
            static if (is(typeof(T == I)) && is(T == I))
               return i;
         return -1;
      }();
   }

But i have no idea how it will do - it appears to be faster than the std one,
but i couldn't really test it, because the std one keeps failing when i try
it with a large enough tuple...

artur


More information about the Digitalmars-d mailing list