On 13 Jul 2014, at 23:29, Trygve Inda <cocoa...@xericdesign.com> wrote:
> NSNumber just seem a bit more flexible since they can be added to
> dictionaries (such as in the userInfo of a Notification).

 NSNumber is more complicated to use (constant calls to integerValue and 
valueWithInteger: etc. to actually work with them) and carries a bit more 
overhead (it creates a new NSObject subclass on the heap every time, while an 
NSInteger can be created directly on the stack). In an ideal world, everything 
in ObjC would be a real object, but in practice, you need to optimize this 
aspect.

A naive estimate of the size of an object consists of a length (internally kept 
by malloc), an isa pointer, and the actual payload (in this case one 
NSInteger). So you get a size of 8 + 8 + 8, which triples the amount of memory 
needed for each number (with tagged pointers and attached data it can go up or 
down, but it’s a good ballpark). Add to that the actual pointer in the object 
that refers to it, which is another 8 bytes. This means 3x more data flows 
through the CPU caches. It also destroys memory locality, because the NSNumber 
gets allocated somewhere in free memory, and not near the object that 
references it.

And accessing the number incurs one polymorphic method call. Method calls are 
fast, but since you’re not really doing polymorphism, it’s orders of magnitude 
slower than just directly accessing an NSInteger and using the CPU’s built-in 
instructions. You’re paying for a lot that you’re never using.

So in summary:

- NSNumber is slower
- NSNumber is larger
- NSNumber requires you to write more code, which means you can make more bugs
- NSNumber has lots of neat features that you’re not really using right now 
(the flexibility you mention above)

In short, unless you’re actively using the flexibility of NSNumber right now, 
you do not want to use it. Given bindings are for UI updates, and the UI 
generally only updates in response to user interaction (and users perform an 
action about every few seconds, which might as well be an ice age apart as far 
as modern CPUs are concerned), it’s usually better to pay the overhead of 
creating a new NSNumber the moment you need it to wrap your number, instead of 
always having one even when you don’t need it.

But keep in mind, premature optimization, root of all evil, yadda, yadda, 
yadda...

Cheers,
-- Uli Kusterer
“The Witnesses of TeachText are everywhere...”
http://zathras.de


_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to