I have a plist with 3200 dictionaries. Each dictionary has 20 key/values. What's the best way to search through it?
I have a string called "id" and what I am doing right now is, iterating through all the elements of the array, asking each element (dictionary) for the value of key "id", comparing that id 开发者_JAVA百科with other id i have, and if it's found, break.
This is really slow, like I can see a lag of about 1-2 seconds. Is there a better way? Thanks
What you're doing now is an O(n) operation (linear in the number of items in the list). You can get a "constant time" O(1) lookup if you keep another "lookaside" data structure that helps you index into your list.
Before you write the 3200 item list of dictionaries, create one more special dictionary that maps your IDs to indexes in the big array. In other words, each key will be an ID and its value will be an NSNumber with the index number into the big array. Then save this also (either in the same plist or a separate one).
Then when you need to do a lookup, just do -objectForKey:
in the lookaside dictionary, which will immediately give you back the index of the entry you're looking for.
Just make sure your lookaside dictionary is always in sync if you update them with live data. Note that this also assumes your IDs are unique (it sounds like they are).
Why don't you use a SQLite database?
The first thing I notice is that it seems you're always searching on the same id
key. If that's the case, then you should sort your array of dictionaries according to id
. You can then do a binary search on the sorted array. Result: finding any dictionary by id
takes a maximum of 12 operations. By contrast, a linear search through 3200 items averages 1600 operations and might need as many as 3200.
Core Data might be a very good solution here if you need to search on several different keys, and if all those dictionaries have the same keys. NSManagedObject works a lot like NSMutableDictionary, but the framework will take care of indexing for you, and searching is fast and relatively easy.
精彩评论