When you have to deal with numbers for anything else than short computation, is it a loss of time and energy using always NSNumber ?
What's the best approach ?
When you have to deal with numbers for anything else than short computation, is it a loss of time and energy using always NSNumber?
Well, NSNumber
generally has to go through the allocation and reference counting hoops to create, so that takes a lot longer than creating a float on the stack.
As well, NSNumber
is an immutable type, so it doesn't make a whole lot of sense to set it often because every time it changes, you have to allocate a new instance. There are a few optimizations they make, but it's still huge overhead relative to creating a float on the stack. Using builtins will also require less memory than NSNumber
more often than the other way around.
What's the best approach?
I just use builtins (e.g. float
, int
) unless I need an NSNumber
. Details and rationale here.
Use whichever is appropriate to your task.
For example, if you are computing rects for drawing use CGFloat because that is what rects use.
NSNumber on the other hand is really good for situations where you need multiple representations of a number (i.e., you need to use it a float and an int).
NSInteger
, NSUInteger
, CGFloat
, etc are simple types and correspond to int, unsigned int and float. NSNumber
is an Objective-C class, a subclass of NSValue
to be specific. You can create an NSNumber
object from a signed or unsigned char, short int, int, long int, long long int, float, double or BOOL.
One of the primary distinctions is that you can use NSNumber
in collections, such as NSArray
, where an object is required. NSInteger
is a simply an integer, NSNumber
is an object.
For performance reasons, if you can, use primitive types (like int, float). However, sometimes you cannot avoid NSNumber
,
Using NSInteger & CGFloat allows your code to run properly on all architectures, 32/64-bit. If you used int/float and compiled your code for a 64-bit architecture, it likely would not operate correctly on a 32-bit system. Additionally, if Apple ever released a 128-bit system your NSInteger/CGFloat code would still work there too (assuming Apple updated the definitions of NSInteger & CGFloat, which they likely would).
Yes, it's a significant loss of time always using NSNumber