struct vs class benchmark (was Re: Give struct the status it deserves)

Rioshin an'Harthen rharth75 at hotmail.com
Mon Mar 27 02:18:49 PST 2006


[sorry, couldn't resist :P]

"Hasan Aljudy" <hasan.aljudy at gmail.com> wrote:
> Heh, this is so flawed.
>
> it's got nothing to do with classes vs. structs.
>
> The benchmark is designed so that the struct version runs faster than the 
> class version.
>
> change the class version to:
>
> Point p = new Point();
> for (uint i = 0; i < n; ++i)
> { Point.count += p.x;
> // delete p;
> }
>
> and the struct version to:
>
> for (uint i = 0; i < n; ++i)
> {
> Point * p = new Point();
> Point.count += p.x;
> }
>
> These programs don't logically do anything different. However, the class 
> version now runs much much faster than the struct version.

Heh, this is so flawed.

The benchmark is designed so that the class version runs faster than the 
struct version.

change class version to:

for (uint i = 0; i < n; ++i)
{
Point p = new Point();
Point.count += p.x;
// delete p;
}

and the struct version to:

Point p;
for (uint i = 0; i < n; ++i)
{
Point.count += p.x;
}

> on my machine:
> >class
> 100000000
> operation took 0 m 0.25 s
>
> >struct
> 100000000
> operation took 0 m 15.265 s

on my machine:
>class
100000000
operation took 0 m 43.594 s

>struct
100000000
operation took 0 m 0.218 s

> Try to come up with a more realistic example, and optamize both versions. 
> This way, you can prove that it's the class vs. struct issue and not an 
> optimization issue.

Maybe you should try to come up with a more realistic example, and optimize 
both. Now you optimized the class version, but not the struct version. It's 
easy to claim classes as faster when you selectively optimize one and not 
the other.

I intentionally optimized the other way around. If your "optimization" 
proves classes are faster, then mine proves structs are faster. And the code 
is still the same - there's no logical difference in how they work (except 
for garbage collecting much more in the class version, as you had in the 
struct version).

To be sure, if both are optimized:

// struct
Point p;
for (uint i = 0; i < n; ++i)
{
p.count += p.x;
}

// class
Point p = new Point();
for (uint i = 0; i < n; ++i)
{
p.count += p.x;
// delete p;
}

the times for the class version change to:

>class
100000000
operation took 0 m 0.25 s

which is equivalent with the 0.218 s it took for the struct version.

If you want to prove classes faster than structs, please don't go about it 
optimizing only the class version and not the struct one. Otherwise, you end 
up looking like a fool. 





More information about the Digitalmars-d mailing list