Lets say I have a Student class as below:
class Student {
NSNumber *id;
NSString *lastName;
NSString *firstName;
}
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.
Assume I create a dictionary called studentsFirstNameDictionary.
So while adding objects to students array, I can do
Student objStudent = [[Student alloc] init];
objStudent.Id = someId;
objStudent.firstName = someName;
objStudent.lastName = someLastName;
[studentsDictionary setValue:iterationCounter forKey:objStudent.firstName];
[students addObject:objStudent];
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:
-(Student*)getStudentByFirstName:(NSString *)firstName {
int idxOfStudent = [ studentsDictionary valueForKey:firstName];
return [students idxOfStudent];
}
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?
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.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.
I don’t think you need the array at all.
Create your Student objects:
To look up a student by
firstName:To get all Student objects from
studentsDictionary, useThis assumes you will only be finding students by their
firstNameattribute however.. @rickster’s solution might be better in general