Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which method of checking to see if a NSDictionary contains a particular key is faster?

I can test for the presence of a key in an NSDictionary in two ways:

BOOL containsKey = [[dictionary allKeys] containsObject:foo];  BOOL containsKey = ([dictionary objectForKey:foo] != nil); 

which method is faster, and why?

like image 947
alfwatt Avatar asked May 06 '09 20:05

alfwatt


1 Answers

A hash lookup should be faster in general than going over all the dictionary keys, creating an array from them (memory allocation is relatively expensive) and then searching the array (which can't even be a binary search since the array is not sorted).

For the sake of science, though, I made two executables that just execute each style 1 million times and timed them.

With allKeys:

real    0m4.185s user    0m3.890s sys     0m0.252s 

With objectForKey:

real    0m0.396s user    0m0.189s sys     0m0.029s 

Obviously, various factors can influence this — size of the dictionary, caching the allKeys return value, etc. I wouldn't expect there to be a case in which the array search is faster than the dictionary lookup, though.

like image 169
Chuck Avatar answered Oct 08 '22 19:10

Chuck