IOS文字游戏。验证词性能

标签 ios objective-c dictionary cpu-word

<分区>


想改进这个问题吗? Update the question所以它是on-topic用于堆栈溢出。

关闭 10 年前

我正在构建一个拼字游戏,但在使用单词词典时遇到了一些问题。它包含约 700,000 个单词,大约 18 MB 大小。

现在,我正在将整个字典加载到一个数组中,这在 iPhone 4 上需要 12 秒。

wordList = [NSMutableArray arrayWithContentsOfFile: [[self applicationDocumentsDirectory] stringByAppendingString:@"/wordlist.plist"]];

我有两个问题:

  1. 是否有更好的方法来更快地加载单词列表和/或减少内存?

  2. 从一组字母中提取所有可能的单词大约需要 12 秒。有可能让它更快吗?这是代码:

    -(NSMutableArray *)getValidWords:(NSString *)letters{
        NSMutableArray *list = [[NSMutableArray alloc] init];
    
        for (int i = 0, c = [wordList count]; i < c; i++){
        if ([self isWordValid: [wordList objectAtIndex: i] forLetters:letters]){
            [list addObject:[wordList objectAtIndex: i]];
        }
    }
    
    return list;
    

    - (BOOL)isWordValid:(NSString *)word forLetters:(NSString *)ltrs{
        int i, z;
        NSRange range;
        BOOL found;
        static NSMutableString *letters = nil;
    
        if ([word length] < 2) return NO;
    
        if(letters == nil) {
            letters = [[NSMutableString alloc] initWithString:ltrs];
        }
        else {
            [letters setString: ltrs];
        }
    
        found = NO;
        range.length = 1;
        for(i = 0; i < [word length]; i++){
            for(z = 0; z < [letters length]; z++){
                if([word characterAtIndex:i] == [letters characterAtIndex:z]){
                     range.location = z;
                     [letters deleteCharactersInRange: range];
                     found = YES;
                     break;
                }
           }
           if (found == NO){
                return NO;
           }
    
           found = NO;
      }
    
      return YES;
    }
    

最佳答案

你需要做一些改变来加快速度。

  1. 使用快速枚举代替旧的 C 风格循环。

  2. 避免大量方法调用。

  3. 尽可能使用 NSPredicate 和/或 Regex。


每当你写[letters length]一个方法被调用,而不是找到它数百万次(这是在嵌套循环的第三层内),将它存储在一个变量中并使用它。

快速枚举:代替for(int i=0; i<[someArrays count];i++)使用 for(id object in someArrays) .

关于IOS文字游戏。验证词性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14337153/

上一篇:ios - 我应该在哪里放置检查它是否为 iphone 5 的 bool 方法?

下一篇:iphone - 在 RSA 解密中将 uint8_t 转换为 NSString

相关文章:

ios - 确认 iPhone 用户

ios - 如何在HeaderDoc中添加多行注释

ios - UIView 的 viewDidLoad?

python - 在字典键上使用 set

python - scipy.io.loadmat 嵌套结构(即字典)

ios - 保持两个 Sprite 之间的恒定距离

ios - 如何让您的页面在虚拟键盘覆盖时将输入元素滚动到 View 中?

ios - 制作一个 iOS 框架 : including 3rd party libraries and code

objective-c - 来自 UIView 的图像

dictionary - 定义一个空的 Dict,其中值是抽象类型的子类型