Fragilerus
Fragilerus

Reputation: 1899

struct vs class

This applies .NET. I am looking to write a spatial mapping application. There will be several polygons in memory at once (on the order of 30 - 50 polygon). each polgon has a collection of LatLong points. the collection can range from 10 to 200 per polygon. However, there are alot of calculations that will be done using the points, which is why (for performance) I want to make the LatLong a struct. However I am weary do to the large number of LatLong that will be in memory. Any insight to this will be appreciated. To recap: I want to know if I shold make the LatLong a struct because I want performance ont the calculation, or a class because of the number of latLongs that will be in memory at one.

Upvotes: 3

Views: 1780

Answers (4)

Justin Morgan
Justin Morgan

Reputation: 30760

The answer to this is going to depend on your resource priorities, what's in the class/struct, and how you're using it. I suggest you figure out what your memory/performance resources are like, then do a lot of testing of both implementations to see how they fit in those resource parameters. If possible, try to test the actual operations you expect to perform.

MSDN also offers some good guidance on when and when not to use structs. From the article:

Do not define a structure unless the type has all of the following characteristics:

  • It logically represents a single value, similar to primitive types (integer, double, and so on).
  • It has an instance size smaller than 16 bytes.
  • It is immutable.
  • It will not have to be boxed frequently.

Upvotes: 10

Brandon Moretz
Brandon Moretz

Reputation: 7621

In general, if you're going to have a large collection of simple objects where the data contained in them won't change once instantiated (your latLongs sound like they're basically data containers) then I would personally use an immutable struct.

Upvotes: 1

Doc Brown
Doc Brown

Reputation: 20044

Make two test implementations with a representative calculation, one with a struct and one with a class, and measure, I repeat measure (!!!) the performance. To my experience it very likely that any prejudice about the expected performance turns out beeing totally wrong in such kind of situations.

Upvotes: 0

Gabe
Gabe

Reputation: 86718

Whether you should do one or the other depends entirely on your application. I would try both ways and see which one is faster. That's what I do when I have that question.

Upvotes: 1

Related Questions