0

I want to pass some data to my object and there are two options for me.

Regarding memory - what's more effecient? To declare three properties or to to declare one NSDictionary using initWithCapacity:3?

jscs
  • 63,694
  • 13
  • 151
  • 195
alexhajdu
  • 410
  • 5
  • 13

2 Answers2

2

Declaring 3 properties will use less memory and be more performant than using an NSMutableDictionary.

Using properties also makes your code easier to read and allows your compiler to help you with type-safety.

Another consideration, is that you can't store nil in a collection.

EDIT:

As far as memory is concerned, the only difference between the 2 options that you mentioned is that the NSDictionary requires its own memory in the heap. The objects themselves will still require the same memory in the heap either way.

Jeff Wolski
  • 6,332
  • 6
  • 37
  • 69
  • 2
    Can you provide some evidence for your performance assertion? – jscs Apr 10 '13 at 19:08
  • 3
    In a property, the memory address of the object is stored in the backing `ivar`. In a `NSDictionary` a hash-table lookup has to be done to get the address of the object. – Jeff Wolski Apr 10 '13 at 19:11
  • There's a secondary lookup for ivars, too: http://www.sealiesoftware.com/blog/archive/2009/01/27/objc_explain_Non-fragile_ivars.html. I don't necessarily disagree, but can you provide some _evidence_ for your performance assertion? – jscs Apr 10 '13 at 19:14
  • 1
    You have to do that lookup anyway to get ahold of the `NSDictionary`, so that gives you 2 lookups instead of just one for an ivar in a property. – Jeff Wolski Apr 10 '13 at 19:18
2

I would advocate for using properties, but not because of a performance issue; simply because I think it's more readable and less error-prone—you can make the dictionary approach clean by using key constants, but it's extra work.

The bottom line here, for me, is that until Instruments shows you that you're spending a significant amount of time or memory on these objects, you should take the path of readability and clarity. It's highly unlikely that it's going to matter if you shave a few cycles or a few bytes. But even if it does, it's not going to be a huge job to refactor the approach you take for an object initialization of three parameters.

Seamus Campbell
  • 17,816
  • 3
  • 52
  • 60