alicooke
alicooke

Reputation: 118

Optimum memory management for NSMutableArrays

A quick question that I really need answered:

Which uses more memory?

A NSMutableArray with a million objects OR a million NSMutableArrays with one object?

Will there even be a difference?

Upvotes: 2

Views: 60

Answers (2)

justin
justin

Reputation: 104698

A million NSMutableArrays with one object would consume more memory.

Suppose a basic NSMutableArray implementation which has a pointer and a size for its elements:

  • the pointer would be 4 to 8 bytes
  • the size would be 4 to 8 bytes
  • then each instance would require two allocations (one for the object, one for the array), which means those addresses are tracked someplace.
  • add a pointer for isa, another 4 to 8 bytes

Now this is not necessarily exactly how NSMutableArray is implemented, but it gives you an idea of memory cost for each instance in a general purpose implementation.

So would you rather take the sum of all those parts and:

  • add 1000000 * sizeof(int*)
  • or multiply it by 1000000?

That should give you an idea that 1M arrays will consume much more memory. Of course, you can test this using Instruments if you need real numbers.

Upvotes: 1

Catfish_Man
Catfish_Man

Reputation: 41801

A million arrays would use much more memory.

Upvotes: 1

Related Questions