Avoid initializing a struct field.

jerro a at a.com
Mon May 6 12:01:42 PDT 2013


On Monday, 6 May 2013 at 15:15:47 UTC, Steven Schveighoffer wrote:
> On Sat, 04 May 2013 14:11:02 -0400, jerro <a at a.com> wrote:
>
>> Is there a way to avoid default initializing a struct field in 
>> D? The following doesn't seem to work:
>>
>> struct Foo
>> {
>>     int[42] buffer = void;
>>     int bar;
>> }
>>
>> I know I can do this:
>>
>> Foo foo = void
>>
>> But then all fields are uninitialized.
>
> Foo.init must exist, and be filled with *something*.  Is it 
> useful to FORCE buffer to not have 0 values?  Or is it that you 
> don't care what it has?  In the latter, is it terrible that 
> it's 0?

I don't care what it contains, I just want to avoid
initialization for performance reasons. I have something like
this:

struct Foo(size_t maxNItems)
{
      Item[maxNItems] buffer;
      size_t nItems;
      size_t addItem(...){ ... }
      void processItems(...){...}
}

The user of Foo can add up to maxNItems items and then run some
algorithm on them. Now say that Foo needs to support up to, say,
a thousand items, but in most cases just a few of them will be
added. In this case default initialization can take way more time
than the actual algorithm.


More information about the Digitalmars-d-learn mailing list