Note that there are some explanatory texts on larger screens.

plurals
  1. POFaster NSArray lookup using NSDictionary storing indices as values
    primarykey
    data
    text
    <p>Lets say I have a Student class as below:</p> <pre><code>class Student { NSNumber *id; NSString *lastName; NSString *firstName; } </code></pre> <p>Now when I get the records of all the students from a web service, I have an NSArray that stores records for all the students. At some point of time I need to look up the array to find a particular student's record based upon first name. </p> <p>Assume I create a dictionary called studentsFirstNameDictionary.</p> <p>So while adding objects to students array, I can do </p> <pre><code>Student objStudent = [[Student alloc] init]; objStudent.Id = someId; objStudent.firstName = someName; objStudent.lastName = someLastName; [studentsDictionary setValue:iterationCounter forKey:objStudent.firstName]; [students addObject:objStudent]; </code></pre> <p>I want to know if it is a good idea to create this dictionary to speed up the look up as below. Also please assume that in any case the array is required and for fast lookup I am creating other dictionaries too storing the last name and id as keys and indices as values like above:</p> <pre><code>-(Student*)getStudentByFirstName:(NSString *)firstName { int idxOfStudent = [ studentsDictionary valueForKey:firstName]; return [students idxOfStudent]; } </code></pre> <p>Do you think this approach is performance wise better than having to iterate through the students array and compare the first name and return the matching student record?</p> <p>I always need the students array because I need to populate a table view with that array. I am wondering if it is wise to create multiple dictionaries while populating the array so that I can look up a student record faster by fist name, last name or Id?</p> <p>P.S.: For sake of simplicity, consider that all students have unique first name, last name and id so there will not be any issue while creating dictionaries storing first name, last name or ID as a value.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload