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

Dave Dave_member at pathlink.com
Sun Mar 26 20:11:37 PST 2006


These run as the same speed on my system, which is pretty cool since the
accessor function for class Point.x is vitual. If you finalize it the class
version is actually faster. No doubt the OP has a point when you try to alloc.
classes in a tight loop, and I'd agree that stack allocated classes would be
great, but if you can work around the allocation bottleneck then classes tend to
be faster and easier to code because they are passed around by reference w/o
pointer syntax.

class Point
{
static int count = 0;
int _x = 1;
int x() { return _x; } // this is vitual
}

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

;---

struct Point
{
static int count = 0;
int _x = 1;
package int x() { return _x; }
}

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

In article <e07ka1$2kml$1 at digitaldaemon.com>, Hasan Aljudy says...
>
>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.
>
>on my machine:
> >class
>100000000
>operation took 0 m 0.25 s
>
> >struct
>100000000
>operation took 0 m 15.265 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.
>
>Hong wrote:
>> Ok, even people are telling me that class is not slower, I have decided to make
>> a benchmark to test them out. Here they are,
>> 
>> Version using struct
>> http://members.iinet.net.au/~honglee/benchmark/benchmarkstruct.d
>> 
>> Version using class
>> http://members.iinet.net.au/~honglee/benchmark/benchmarkclass.d
>> 
>> On my computer, the struct version runs 300 times faster than the class version.
>> Interestingly, deleting the object explicitly in the class version actually
>> slowed the program even further.
>> 
>> The difference seems real.
>> 
>> In article <e07506$1ss2$1 at digitaldaemon.com>, Hasan Aljudy says...
>> 
>>>What's wrong with classes?!
>>>
>>>Classes won't make your code slow.
>>>
>> 
>> 
>> 
>





More information about the Digitalmars-d mailing list