objective-c - 将单词列表字典加载到数组中的最快方法?
<p><p>我正在开发一个基于单词的游戏,我需要将我的 180,000 单词词典 (1.9MB) 加载到一个数组中,以便求解算法可以使用它。字典只是每行一个单词,像这样:</p>
<pre><code>a
ab
abs
absolutely
etc
...
</code></pre>
<p>现在我正在使用以下代码将该文件加载到数组中:</p>
<pre><code>NSString *txtPath = [ pathForResource:@"dict" ofType:@"txt"];
NSString *stringFromFile = [
initWithContentsOfFile:txtPath
encoding:NSUTF8StringEncoding
error:&error ];
for (NSString *word in ) {
;
}
</code></pre>
<p>这在 iPhone 4 上大约需要 3-4 秒。在较旧的 iOS 设备上可能会更慢。有没有更快的方法来做到这一点? </p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>您可以使用 Grand Central Dispatch 或 GCD 在后台轻松执行此操作,离开主线程。</p>
<pre>dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0),^(void){
NSString *txtPath = [ pathForResource:@"dict" ofType:@"txt"];
NSString *stringFromFile = [
initWithContentsOfFile:txtPath
encoding:NSUTF8StringEncoding
error:&error ];
for (NSString *word in ) {
;
}
});
</pre>
<p>I wrote the enclosing dispatch code from memory, but it's close (if not correct) and I think you get the idea.</p>
<p><b>EDIT:</b> You can execute this code on the main thread, but what happens is a non-main-thread dispatch queue is where your code executes, thereby NOT blocking the UI.</p>
<p>You can improve the performance of your code here a little bit by replacing the <code>for</code> loop with just this:</p>
<pre><code>];
</code></pre>
<p>应该不需要迭代 <code>-componentsSeparatedByString:</code> (一个数组)的结果,只是将它们放入 <em>another</em> 数组中。有了 180K 字,这应该可以节省大量时间。</p></p>
<p style="font-size: 20px;">关于objective-c - 将单词列表字典加载到数组中的最快方法?,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/10146171/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/10146171/
</a>
</p>
页:
[1]