Give struct the status it deserves

Dave Dave_member at pathlink.com
Mon Mar 27 09:06:37 PST 2006


In article <e0948b$1ihl$1 at digitaldaemon.com>, Oskar Linde says...
>
>Stewart Gordon wrote:
>> Hong wrote:
>>> Structs are second class citizens of... or maybe refugees of D, they 
>>> are victims
>>> of discrimination.
>>> Following are the reasons:
>
>[snip]
>
>>> 4. structs cannot have constructor, "static opCall" is best you can do.
>> 
>> What's wrong with that?  Do you simply miss the word "new" in uses of 
>> static opCall?
>
>The problem with not having real constructors is that you can not 
>guarantee that your struct gets initialized correctly.
>
>>> 5. structs are more efficient? Not when structs are passed around by 
>>> value. To
>>> change a struct member: 1. make a copy 2. change the copy 3. Copy the 
>>> copy back
>>> into the original location. Two damned copies for.... efficiency.
>> 
>> If you want classes, you know where to find them.
>
>Small structs (the cases were structs are most useful) can often more 
>efficient to pass by value than by reference.
>

You know, with all of the talk of cache locality and what-not w.r.t. passing
small structs by value vs. reference, I've yet to see the "conventional wisdom"
(that passing byref is faster) proven wrong, even in larger programs where there
has to be things being constantly being moved in and out of cache, etc. I'm not
saying that is always the case, but 'often' above is pretty strong there. I'd
say at best "sometimes" is a better phrase.

// Yes, yes I know this is may not reflect a typical 'real world' program
//  But still there is a 4x difference on my AMD64 and P4 ('modern
//  processor') boxen, with byref being the faster.

import std.stdio, std.date;

struct S { int i, j, k; }

class C { int i, j, k; }

void main()
{
const int y = 100_000_000;
{
S s;
d_time st = getUTCtime();
for(int x = 0; x < y; x++)
{
fooS(s);
}
d_time en = getUTCtime();
writefln("struct byval: ",(en-st) / cast(double)TicksPerSecond);
}

{
S s;
d_time st = getUTCtime();
for(int x = 0; x < y; x++)
{
fooS2(&s);
}
d_time en = getUTCtime();
writefln("struct byref: ",(en-st) / cast(double)TicksPerSecond);
}

{
C c = new C;
d_time st = getUTCtime();
for(int x = 0; x < y; x++)
{
fooC(c);
}
d_time en = getUTCtime();
writefln("class:        ",(en-st) / cast(double)TicksPerSecond);
}
}

void fooS2(S* s) {  s.i = s.j = s.k = 0; }

void fooS(S s) { s.i = s.j = s.k = 0; }

void fooC(C c) { c.i = c.j = c.k = 0; }





More information about the Digitalmars-d mailing list