Block statements and memory management

H. S. Teoh hsteoh at quickfur.ath.cx
Sat Mar 16 12:40:19 UTC 2019


On Sat, Mar 16, 2019 at 01:21:02PM +0100, spir via Digitalmars-d-learn wrote:
> On 16/03/2019 11:19, Dennis via Digitalmars-d-learn wrote:
[...]
> > 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.
[...]

And to add even more to that: before embarking on micro-optimizations of
this sort, always check with a profiler whether or not the bottleneck is
even in that part of the code. Often I find myself very surprised at
where the real bottleneck is, which is often nowhere near where I
thought it should be.  Also, check with a memory profiler to find out
where the real heavy memory usage points are.  It may not be where you
thought it was.

Generally speaking, in this day and age of highly-optimizing compilers,
premature optimization is the root of all evils, because it uglifies
your code and makes it hard to maintain for little or no gain, and
sometimes for *negative* gain, because by writing code in an unusual
way, you confuse the optimizer as to your real intent, thereby reducing
its effectiveness at producing optimized code. Don't optimize until you
have verified with a profiler where your bottlenecks are. It takes a lot
of time and effort to write code this way, so make it count by applying
it where it actually matters.

Of course, this assumes you use a compiler with a powerful-enough
optimizer.  I recommend ldc/gdc if performance is important to you. Dmd
compiles somewhat faster, but at the cost of poorer codegen.


T

-- 
The early bird gets the worm. Moral: ewww...


More information about the Digitalmars-d-learn mailing list