Closures and memory allocation

Anonymouse zorael at gmail.com
Sat Jun 22 16:52:07 UTC 2019


I'm looking into why my thing does so many memory allocations. 
Profiling with kcachegrind shows _d_allocmemory being called upon 
entering a certain function, lots and lots of times.

It's a function that receives concurrency messages, so it 
contains nested functions that close over local variables. Think 
receiveTimeout(0.seconds, &nested1, &nested2, &nested3, ...) with 
13 pointers to nested functions passed.

When entering the following function, does it allocate:

1. 0 times, because while there are closures defined, none is 
ever called?
2. 2 times, because there are closures over two variables?
3. 20 times, because there are 20 unique closures?

void foo()
{
     int i;
     long l;

     void foo01(bool b_) { i += 1; }
     void foo02(string s) { i += 2; }
     void foo03(int n) { i += 3; }
     void foo04(float f) { i += 4; }
     void foo05(double d) { i += 5; }
     void foo06() { i += 6; }
     void foo07() { i += 7; }
     void foo08() { i += 8; }
     void foo09() { i += 9; }
     void foo10() { i += 10; }
     void foo11() { l += 11; }
     void foo12() { l += 12; }
     void foo13() { l += 13; }
     void foo14() { l += 14; }
     void foo15() { l += 15; }
     void foo16() { l += 16; }
     void foo17() { l += 17; }
     void foo18() { l += 18; }
     void foo19() { l += 19; }
     void foo20() { l += 20; }

     auto f01 = &foo01;
     auto f02 = &foo02;
     auto f03 = &foo03;
     auto f04 = &foo04;
     auto f05 = &foo05;
     auto f06 = &foo06;
     auto f07 = &foo07;
     auto f08 = &foo08;
     auto f09 = &foo09;
     auto f10 = &foo10;
     auto f11 = &foo11;
     auto f12 = &foo12;
     auto f13 = &foo13;
     auto f14 = &foo14;
     auto f15 = &foo15;
     auto f16 = &foo16;
     auto f17 = &foo17;
     auto f18 = &foo18;
     auto f19 = &foo19;
     auto f20 = &foo20;
}


More information about the Digitalmars-d-learn mailing list