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

Wolfgang Draxinger wdraxinger at darkstargames.de
Mon Mar 27 03:40:21 PST 2006


Derek Parnell wrote:

>> 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.

It makes no difference for the use of objects if they are on the
heap or on the stack. Both are only portions of the same address
space (and may even clash if they interpenetrate).

The only thing that makes things slow is the allocation of heap
memory which may cause the garbage collector to kick in. But
once the memory is allocated it can be used as fast as stack
memory.

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

I don't see a reason for this. There's no difference in accessing
the data. Put a struct on the stack, the compiler will compile
it to access it indirectly (i.e. by "pointers"). Allocate a
class on the heap, it get's accessed in the very same way.

As a rule of thumb: Any data you going to work with in a D
program is encapsulated in classes. Stuff that gets dumped into
files or memory goes into structs. It's that simple.

-- 
Wolfgang Draxinger




More information about the Digitalmars-d mailing list