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

Derek Parnell derek at psych.ward
Mon Mar 27 02:30:49 PST 2006


On Mon, 27 Mar 2006 17:12:34 +1100, Hasan Aljudy <hasan.aljudy at gmail.com>  
wrote:

> Derek Parnell wrote:
>> On Sun, 26 Mar 2006 19:57:08 -0700, Hasan Aljudy 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.
>>   I think that you're amendment does not make them logically or  
>> otherwise the
>> same. Your class version does one GC operation (create a new object) but
>> your struct version does one GC operation per iteration - a new Point is
>> allocated for every iteration.
>>
>
> The program doesn't really do anything, you know.

Wow! Really?! Are you sure?

> Creating a new instance serves no purpose at all. So, as an  
> optimization, you can do away without constant allocation; just reuse  
> the same object.

I think you are deliberately missing the point, Hasan. I thought the point  
was to show that heap-allocated things are inherently slower than  
stack-allocated things. The original example didn't do a good job of that  
but my subsequent example does I believe. Can you please comment on my  
example code?

> The example serves very well to illustrate how slow it is to allocate  
> millions of objects on the heap in one go.
> However, it provides no proof that, in pratical situations, structs are  
> much much faster than classes. Which is basically what the example tries  
> to hint at.

But I think my example does show that classes (allocated on the heap) are  
slower than structs whether allocated on the heap or on the stack.

Classes are slower than structs. Prove otherwise. I'm happy to be shown  
that I'm wrong.

-- 
Derek Parnell
Melbourne, Australia



More information about the Digitalmars-d mailing list