Janum Trivedi
Janum Trivedi

Reputation: 1690

Finding object using NSDictionary valueForKey vs. iterating through NSArray

I'm working on a simple iOS caching system for some images. I need to keep track of the UIImage itself and its identifier. Now, I'm trying to figure out which is a faster/more efficient way to access the correct cached image.

Option 1:

for (CachedImage* image in [cachedImageArray]
{
  if ([[image identifier] isEqualToString:@"id_12345"]
  { 
    // use that image
  }
}

Option 2:

UIImage* imageToRetrieve = [cachedImagesDictionary objectForKey:@"id_12345"

Is there any benefit from using one method or the other? And if so, is it non-negligible? Thanks.

Upvotes: 2

Views: 498

Answers (3)

carlosfigueira
carlosfigueira

Reputation: 87228

Dictionaries will most likely be faster, since they'll use some hashing algorithm to make the retrieval efficient (usually O(1) instead of O(n)). It will be non-negligible if the number of elements in your cache is large.

from CFDictionary.h

Computational Complexity
The access time for a value in the dictionary is guaranteed to be at worst O(lg N) for any implementation, current and future, but will often be O(1) (constant time). Insertion or deletion operations will typically be constant time as well, but are O(N*lg N) in the worst case in some implementations. Access of values through a key is faster than accessing values directly (if there are any such operations). Dictionaries will tend to use significantly more memory than a array with the same number of values.

Upvotes: 7

followben
followben

Reputation: 9197

Like H2CO3 says, I'd choose Option 2 for readability.

However, if it's truly a cache (i.e. you're happy for the OS to automatically remove objects from the cache if memory is tight), I'd use NSCache over NSDictionary:

// Setup the cache
UIImage *myImage = [UIImage imageNamed:@"blah"];
NSCache *imageCache = [[NSCache alloc] init];
[imageCache setObject:myImage forKey:@"id_12345"];   

// Sometime later...
UIImage* imageToRetrieve = [imageCache objectForKey:@"id_12345"];

Upvotes: 1

user529758
user529758

Reputation:

Is there any benefit from using one method or the other?

Yes.

UIImage *imageToRetrieve = [cachedImagesDictionary objectForKey:@"id_12345"];

is much more readable.

(Oh, you meant performance? Don't worry about that. Premature optimization is the root of almost all evil.)

Upvotes: 5

Related Questions