Block statements and memory management

spir denis.spir at gmail.com
Sat Mar 16 12:21:02 UTC 2019


On 16/03/2019 11:19, Dennis via Digitalmars-d-learn wrote:
> On Saturday, 16 March 2019 at 03:47:43 UTC, Murilo wrote:
>> Does anyone know if when I create a variable inside a scope as in
>> {int a = 10;}
>> it disappears complete from the memory when the scope finishes? Or does it 
>> remain in some part of the memory? I am thinking of using scopes to make 
>> optimized programs that consume less memory.
> 
> In general, you want variables to have no larger scope than needed, so in large 
> functions reducing the scope may be useful. When it comes to efficiency however, 
> doing that is neither necessary nor sufficient for the compiler to re-use 
> registers / stack space. I looked at the assembly output of DMD for this:
> ```
> void func(int a);
> 
> void main()
> {
>      {
>      int a = 2;
>      func(a);
>      }
>      {
>      int b = 3;
>      func(b);
>      }
> }
> ```
> Without optimizations (the -O flag), it stores a and b on different places in 
> the stack.
> With optimizations, the values of a and b (2 and 3) are simply loaded in the EDI 
> register before the call.
> Removing the braces doesn't change anything about that.
> The compiler does live variable analysis [1] as well as data-flow analysis [2] 
> to figure out that it's only needed to load the values 2 and 3 just before the 
> function call. This is just a trivial example, but the same applies to larger 
> functions.
> 
> In any case, for better memory efficiency I'd consider looking at reducing 
> dynamic allocations such as new or malloc. Memory on the stack is basically free 
> compared to that, so even if adding lots of braces to your code reduces stack 
> memory, chances are it's a low leverage point.
> 
> [1] https://en.wikipedia.org/wiki/Live_variable_analysis
> [2] https://en.wikipedia.org/wiki/Data-flow_analysis

Just to add a bit on what has been said:
* Register allocation (see wikipedia) is a well-researched area.
* By coding that way, you force the compiler to optimise *a certain way* which 
may prevent it to perform other, more relevant optimisations.
* You cannot beat the knowledge in that domain, it is simply too big and 
complex, just be confident.
diniz



More information about the Digitalmars-d-learn mailing list