iOS开发是否需要缓存UIColor

版权声明:原创文章,未经允许禁止转载! https://blog.csdn.net/mlibai/article/details/51735929

在开发中,发现有的项目对 UIColor 对象进行了缓存。个人感觉,对于 UIColor 这样的对象,其本身记录的信息有限,创建它应该不会对APP性能产生显著的影响的,为此特别写了一个 Demo 验证了一下。主要代码如下:

#import <sys/time.h>

// 获取时间点,精确到微秒
- (double)getCurrentTime {
    struct timeval aTime;
    gettimeofday(&aTime, NULL);
    return (double)aTime.tv_sec + ((double)aTime.tv_usec / 1.0e6L);
}

// 向缓存中添加颜色
- (IBAction)createAColor:(UIButton *)sender {
    // 为了增加搜索命中率,随机颜色只是在一个较小的范围内随机
    CGFloat fRed   = arc4random() % 10 / 10.0;
    CGFloat fGreen = arc4random() % 10 / 10.0;
    CGFloat fBlue  = arc4random() % 10 / 10.0;
    CGFloat fAlpha = arc4random() % 10 / 10.0;
    
    double start = [self getCurrentTime];
    UIColor *color = [UIColor colorWithRed:fRed green:fGreen blue:fBlue  alpha:fAlpha];
    double end = [self getCurrentTime];
    
    [self.cachedColors addObject:color];
    self.resultLabel.text = [NSString stringWithFormat:@"创建一个 UIColor 对象用时:%f,目前共 %ld 种颜色", end - start, self.cachedColors.count];
}

// 搜索颜色
- (IBAction)searchColor:(UIButton *)sender {
    NSInteger fRed   = arc4random() % 10;
    NSInteger fGreen = arc4random() % 10;
    NSInteger fBlue  = arc4random() % 10;
    NSInteger fAlpha = arc4random() % 10;
    
    double start = [self getCurrentTime];
    __block UIColor *findColor = nil;
    // 快速遍历
    [self.cachedColors enumerateObjectsUsingBlock:^(UIColor * obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIColor *color = obj;
        CGFloat red, green, blue, alpha;
        // UIColor 对象,并不是全部都可以取出 RGBA 值,但是本例中的颜色都是 RGBA 的,不做多的讨论。
        [color getRed:&red green:&green blue:&blue alpha:&alpha];
        NSInteger Red, Green, Blue, Alpha;
        // 浮点数可能会出现 3.9999999999 或 4.00000000001 这样的情况,所用四舍五入。
        // 相对于比较浮点数,比较整数误差更小一点
        Red   = round(red * 10);
        Green = round(green * 10);
        Blue  = round(blue * 10);
        Alpha = round(alpha * 10);
        if (fRed == Red && fGreen == Green && fBlue == Blue && fAlpha == Alpha) {
            findColor = color;
            *stop = YES;
        }
    }];
    double end = [self getCurrentTime];
    
    if (findColor != nil) {
        self.resultLabel.text = [NSString stringWithFormat:@"找到,用时:%f", end - start];
    } else {
        self.resultLabel.text = [NSString stringWithFormat:@"未找到,用时:%f", end - start];
    }
}

最终结果:

/**
 *  本文的作用主要是验证是否需要缓存UIColor,结果:
 *  创建一个 UIColor 对象,需要 3 微秒左右;
 *  当缓存中颜色数量较少时,搜索一次所需的时间,与该时间差不多;
 *  但是当在仅容量达到 100 时,搜索一次耗时已经达到 30 微秒;
 *  超过了新创建一个所需的时间,所以,缓存颜色,并不是一个合适的做法。
 */

猜你喜欢

转载自blog.csdn.net/mlibai/article/details/51735929