Structs insted of classes for Performance

anonymous via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Apr 20 12:01:06 PDT 2014


On Sunday, 20 April 2014 at 18:08:19 UTC, Frustrated wrote:
> In D though, I guess because of the GC(but which is why I am 
> asking because I don't know specifically), classes could be 
> much slower due to all the references causing the GC to take 
> longer scan the heap and all that. If allocate or free a lot of 
> classes in a short period of time it also can cause issues IIRC.

(You probably now this, but just so that we're on the same page:)
Structs on the stack are not GC'ed. They don't add garbage, they
don't trigger collections. When you `new` a struct the GC is in
charge again.
Class instances on the heap are GC'ed. Putting them on the stack
isn't typical, and somewhat for experts. After all, if you want
to put it on the stack, you can probably use a (more
light-weight) struct instead.

I'd expect many short-lived objects to not perform very well.
There would be much garbage, it would have to be collected often.
D's GC isn't the best in town. Advice regarding GC performance
often comes down to "avoid collections".

> I just can't remember if there was some other weird reasons why 
> D's classes are, in general, not as performant as they should 
> be. If I remember correctly, I came across a page that compared 
> a few test cases with the GC on and off and there was a huge 
> factor involved showing that the GC had a huge impact on 
> performance.

I guess that shows that it's the collections that are slow. So,
D's classes probably /could/ perform better with a better GC.
That's mostly an issue with the GC implementation, I think, not
so much a consequence from D's design.

Coming back to your original questions:

On Sunday, 20 April 2014 at 15:03:34 UTC, Frustrated wrote:
> So, is the only argument really about performance when creating 
> structs vs creating classes or was there some finer detail I 
> missed?

Yes, it's all about performance, I think. You can write correct
programs using classes for everything.

> Basically that boils down to stack allocation vs heap 
> allocation speed? Which, while allocation on the heap shouldn't 
> be too much slower than stack, the GC makes it worse?

Stack vs heap does make a difference. It's an indirection and
smarter people than me can think about caches and stuff. The GC
does make it worse, especially in its current incarnation.

But then, if you care enough about performance, and you need to
use the heap, then D does allow you to manage your memory
yourself, without going through the GC.


More information about the Digitalmars-d-learn mailing list