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?
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:
- If you store objects in them, you have to be very careful to do your own memory management correctly
- You can't store them in NSArrays without creating an object wrapper (since NSArray is an array of objects)
- You can't hook structs up in Interface Builder — it doesn't know anything about them
- You can't do KVO or KVC with structs
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.
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
's isa
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.