I am optimizing an objective-c application, and within that application there is a large NSString containing about 4000 sentences; don’t ask why… but there is.
It is randomly selecting a sentence and returning it.
This is the code (I shortend the centenses):
NSString *sentences[] = {@"For crying out loud", @"Too much information", @"Tomorrow", @"Tonight", @"I don't know", @"Forever and ever ", @"Lets get high", @"Foreigner ", @"Sick"};
self.responses = malloc(sizeof(self.responses)/sizeof(void*));
memcpy(strings, self.responses, sizeof(sentences)/sizeof(void*));
[...]
[self performSelector:@selector(didRecieveMessage:) withObject:self.responses[rand() % sizeof(self.responses)] afterDelay:rand() % 15 + 2];
Now, this needs to be optimized. I was thinking of including the sentences within the SQLLite Db and call the DB to fetch the random sentence, but are there any better ways to do this? E.g. reading a random line from a text file, or Plist file? And if so, how do I do it?
Memory is of course one of the most important aspects.
Well you could start by not copying the whole array and taking up twice as much memory with the memcpy.
I see some cut and paste fog in here but its pretty apparent that what should have been done is use NSArray for the initial array and not do the memcpy of the entire array.
Other than that put it in sqlite and do a query and you wont have all this stuff in memory. If this is iOS I would definitely dump this data into sqlite. Any kind of ref data that size should not be in memory.
This is prime for Sqlite….