NSMutableDictionary VS NSMutableArray 速度

NSMutableDictionary VS NSMutableArray speed

我正在为从 Parse.com 下载的图像使用缓存。图像用作 UITableView 单元格中 UIButton 的背景图像。图像存储在 NSMutableDictionary 中。代码如下:

    PFUser *user =self.currentUser.friends[(int)indexPath.row*4+i];
    label.text=user.username;

    UIImage *cachedImage = self.images[@(indexPath.row*4+i)];
    if (cachedImage) {
        NSLog(@"Have image");
        [button setBackgroundImage:cachedImage forState:UIControlStateNormal];
    }

    else {
        NSLog(@"Download image");
        //download code

        PFFile *userImageFile = user[@"profilePic"];
        [userImageFile getDataInBackgroundWithBlock:^(NSData *imageData, NSError *error) {
            if (!error) {
                UIImage *image = [UIImage imageWithData:imageData];
                self.images[@(indexPath.row*4+i)] = image;
                [button setBackgroundImage:image forState:UIControlStateNormal];

            }
        }];

    }

该解决方案运行良好,但我意识到,如果我删除一个朋友,我需要将他们从字典中删除,如果我这样做,这意味着我将不得不更改与 UIImages 关联的所有索引。我认为 NSMutable 数组会更好,所以我不必这样做,我可以根据需要插入和删除对象。这会影响应用程序的速度吗?数组比字典效率低吗?

使用字典的全部原因是让项目可以通过 属性 访问,而不是通过数字索引访问。通过使用行索引,您正在破坏拥有字典的目的。

使用更稳定的密钥代替[@(indexPath.row*4+i)],例如图像的username或URL。

如果您想使用数字索引 (indexPath.row),请使用 NSMutableArray.

请注意,只有当您有数千个项目时,您才应该担心速度数组与字典。