Const and enum optimizations

Jonathan M Davis jmdavisProg at gmx.com
Thu Jan 3 10:25:11 PST 2013


On Thursday, January 03, 2013 16:58:11 Phil Lavoie wrote:
> Hi,
> 
> I have a question concerning compiler optimizations and their
> likelihood for const vs. enum declarations.
> 
> I came across some code recently that had a bunch of const
> declarations that were extracted from a C header. In this very
> header, those definitions are in fact #define clauses.
> 
> I was under the impression that those should be translated as:
> header.c:
> #define MY_CONST 1
> ...
> module.d:
> enum {
> MY_CONST = 1
> }
> and not:
> module.d:
> const MY_CONST = 1;
> 
> I thought that MY_CONST enum is more likely optimized since its
> address cannot be taken? But my real question is this: is a
> declaration like MY_CONST (enum) always optimized space wise (for
> dmd)? What is the likelihood of MY_CONST (const) being optimized
> as well?

All enums are effectively copy-pasted when they're used. That's why having 
enums of array literals can be a bad idea.

enum a = [1, 2, 3, 4];
foo(a);
bar(a);

becomes

foo([1, 2, 3, 4]);
bar([1, 2, 3, 4]);

so you get double the allocations. If you do

const a = [1, 2, 3, 4];

then you've declared an actual variable whose address can be taken, and the 
allocation will occur only once.

const variables outside of local scope _won't_ be optimized out of existence,
but at local scope, they may be optimized out by constant folding. The enum
version at local scope is just as likely to be optimized as if you
copy-pasted the value yourself rather than using an enum. But what exactly
dmd ultimately optimizes probably depends on the code, and you'd have to look
at the generated assembly to know for sure.

But if your concern is const variables at module scope being optimized out of 
existence, it is my understanding that they won't be.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list