I'm developing an iPhone 3.1.3 application.
I have a class, called Object2D
, with fields and methods; which represent a shape. Object2D
has a field that represents its size, and another field that represent its type.
Now, I need another class called Pattern
, which is a set of shapes. In Pattern
I'm going to have an array of shapes. From these shapes I only need their size, their type and their location inside pattern, I don't need any method.
I'm wondering it is better to have a new struct that represent a shape instead of using Object2D
class.
I ask this because I think on memory performance. I'm not sure, but struct are smaller than classes and maybe it's better to use them instead of classes.
What do you think?
Objective-C classes are in fact structs, and, provided the instance variables are laid out in the same order as the structure members are, the only difference in size is the 4 or 8 bytes of
NSObject
'sisa
variable.NOTE: the answer above assumes the legacy Objective-C runtime, without the use of
@property
and@synthesize
directives, which could potentially affect their size.If you're looking at memory use, the difference is truly negligible in almost every situation. Objects are one pointer bigger than an equivalent struct.
The greater difference is in how you can use them. Objects can have methods and hierarchies and interact with the rest of Cocoa. With structs, you need to make custom functions for each struct type or hack together a pseudo-object system. On top of that, arbitrary structs don't interact well with the rest of Cocoa (Touch). For example:
In general, if you're working with a Cocoa-like framework, objects are a good default choice. Use structs once you've decided you really need them.