Reputation: 6586
I'm asking for a project in C#, but I assume this question applies to other languages as well. I've heard that massive object creation and destruction causes massive overhead and performance issues. I'm wondering if I can get around this by simply using structs instead of objects.
Upvotes: 0
Views: 181
Reputation: 345
Here is some facts that you must now about struct
and class
in C# :
struct
in C# is faster to create than a class
since it's allocated on the stack and not on the heapstruct
is a value type, class
is a reference type. So working with a reference type (passing it as parameter, copying it, ...) is much faster than working with the value type. see Difference between struct and classstruct
fields are fast to access than class
fields since they are allocated on the stackHere is some facts about how the GC works in .Net :
Knowing all of that and to be short, if you don't want your program to suffer from the GC work, you have to use reference types for objects that will live the longer in your program, and use value types for objects that will be used for a very short time and in a very localized scope.
Upvotes: 2
Reputation: 30813
"Making struct instead of object" - as you term it (I suppose what you mean by object is class) would most likely be of little help since creating struct instance, due to struct's nature, will require you to refer it by value rather than by by reference - and this may (not always) make your memory use heavier
That being said, what you probably need is Flyweight Design Pattern
From https://sourcemaking.com/design_patterns/flyweight:
Flyweight Design Pattern
Intent
Use sharing to support large numbers of fine-grained objects efficiently.
The Motif GUI strategy of replacing heavy-weight widgets with light-weight gadgets.
Problem
Designing objects down to the lowest levels of system "granularity" provides optimal flexibility, but can be unacceptably expensive in terms of performance and memory usage.
Discussion
The Flyweight pattern describes how to share objects to allow their use at fine granularities without prohibitive cost. Each "flyweight" object is divided into two pieces: the state-dependent (extrinsic) part, and the state-independent (intrinsic) part. Intrinsic state is stored (shared) in the Flyweight object. Extrinsic state is stored or computed by client objects, and passed to the Flyweight when its operations are invoked.
Upvotes: 5