Empty struct, any runtime cost?

Nicholas Wilson via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Aug 19 07:05:24 PDT 2015


On Wednesday, 19 August 2015 at 09:54:33 UTC, SimonN wrote:
> Hi,
>
> in a release-like build, I'm using the tharsis profiler, which 
> is a
> frame-based profiler. Zone is a RAII struct that measures how 
> long its own
> lifetime is.
>
>     with (Zone(my_profiler, "zone name to appear in output")) {
>         do_expensive_work();
>         do_some_more_work();
>     }
>     // Zone goes out of scope here
>
> I would like to use this code without modification in a release 
> build
> without profiling. I would rather not put version statements 
> everywhere.
> I have only one version statement in a single file that's 
> included by
> all files doing profiling:
>
>     version (release_with_profiling) {
>         public import tharsis.prof;
>     }
>     else {
>         class Profiler { }
>         struct Zone { this(Profiler, string) { } }
>     }
>
> Using that, the first code sample compiles in the non-profiling 
> build,
> where Zone is an empty struct.
>
> *   Will the empty struct get optimized away completely by the 
> compiler,
>     at least if we pass -O -inline? I'd really like that, I have
>     profiling code in several inner loops.
>

I'd be surprised if it didn't, but you can always check the 
disassembly.
If for some reason either the compiler doesn't remove it (it never
removes classes btw but not sure about structs) or the linker
doesn't discard it you can try -gcsections ( or w/e its called ).

> *   If not, what other approach could be usable to keep 
> boilerplate in
>     most source files to a minimum?
>
> -- Simon



More information about the Digitalmars-d-learn mailing list