iphone - 优化 Cocoa/Objective-C 搜索

标签 iphone objective-c cocoa-touch algorithm optimization

我正在搜索一个包含字典的大型 plist 文件,其中有数万个,每个都有 2 个键/字符串对。我的搜索算法遍历词典,当它在词典中的任一字符串中找到文本匹配项时,就会插入词典的内容。这是它的工作原理:

NSDictionary *eachEntry;
NSArray *rawGlossaryArray = [[NSArray alloc] initWithContentsOfFile:thePath]; // this contains the contents of the plist

for (eachEntry in rawGlossaryArray)
    {
        GlossaryEntry *anEntry = [[GlossaryEntry alloc] initWithDictionary:eachEntry];


        NSRange titleResultsRange = [anEntry.title rangeOfString:filterString options:NSCaseInsensitiveSearch];
        NSRange defResultsRange = [anEntry.definition rangeOfString:filterString options:NSCaseInsensitiveSearch];

        if (titleResultsRange.length > 0 || defResultsRange.length > 0) {
            // store that item in the glossary dictionary with the name as the key
            [glossaryDictionary setObject:anEntry forKey:anEntry.title];

        }
        [anEntry release];
    }

每次执行搜索时,我的 iPhone 应用程序都会有大约 3-4 秒的延迟(至少在设备上是这样;模拟器中的所有内容都运行得非常快)。谁能建议我如何优化此搜索?

最佳答案

如果不查看数据集,我无法确定,但如果您对其进行概要分析,您将花费大量时间在 -rangeOfString:options: 上。如果是这种情况,如果不从根本上改变您用来存储数据的数据结构,您将无法提高性能。

您可能想要构造一些带有指向对象的字符串和子字符串的排序特里树。设置起来要复杂得多,插入其中的成本会更高,但查找速度会非常快。鉴于您正在序列化结构,无论如何昂贵的插入应该不是什么大问题。

关于iphone - 优化 Cocoa/Objective-C 搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1070140/

相关文章:

iphone - 如何在 iPhone 中使用 DES 加密 NSString 值?

ios - 如何在 iOS 中将 pdf 页面转换为图像

ios - 是否有机会针对 EKEventStore 编写单元测试?

cocoa-touch - iBook翻页过渡

iphone - UITableView 怪异!带图片

iphone - Objective-C 和 ARC : Why value stored to during its initialization is never read?

ios - Objective c-只有特定的 UILabel 在 UITableView 中被编辑

objective-c - NSRegularExpression 从 numberOfRanges 方法给出了错误的结果

objective-c - MKAnnotation 删除(处理器重)

ios - 写入流 iOS 时的自旋锁(仅在模拟器上)