繁体   English   中英

优化排序和过滤对象数组

[英]Optimization of sorting and filtering array of objects

我有有效的代码,并希望从中获得更好的性能,因为如果传递更多的数据,它会被漂亮地加载。 但是我不知道该怎么办。

输入:带有logUnits的数组,每个数组包含一个日志事件视图,例如“ 2013-01-16 15:13:00 Hello”和时间数组-该数组仅包含我们有日志事件的时间(2013-01-02,2013 -01-09等)

输出:视图数组,其中每个视图包含同一天的日志单位。

我还可能需要按事件类型过滤日志单元。

这是我的操作方式。

 NSMutableArray *views = [[NSMutableArray alloc] initWithCapacity:times.count];
    @autoreleasepool {

        for(int x = 0; x != times.count; x++)
        {
            UIView *foo = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 400)];
            foo.backgroundColor = [UIColor clearColor];
            int f = 0;
            int h = 0;

            for(int i = 0; i != objectArray.count; i++)
            {
                @autoreleasepool
                {

                    LogUnit *unit = [objectArray objectAtIndex:i];
                    if([[times objectAtIndex:x] isEqual:[unit realTime]]) 
                    {

                        if(![[foo subviews] containsObject:unit.view]) // Look if unit was already added
                        {
                            NSString *number = [NSString stringWithFormat:@"SortLog%i ",[[NSUserDefaults standardUserDefaults] stringForKey:@"ObjectNumber"].intValue];
                            NSString *comp = [[NSUserDefaults standardUserDefaults] stringForKey:number];

                            if([[unit status] isEqualToString:comp] || [comp isEqualToString:NULL] || comp == NULL)
                            {
                                if([unit getEvent] != NULL)
                                {
                                    unit.view.frame = CGRectMake(unit.view.frame.origin.x, f * unit.view.frame.size.height + 30, unit.view.frame.size.width, unit.view.frame.size.height);
                                    [foo addSubview:unit.view];
                                    f++;
                                    h = unit.view.frame.size.height * f;
                                }
                            }
                        }
                    }
                }
            }

            foo.frame = CGRectMake(0,0, 320, h + 30 );
            h = 0;
            [views addObject:foo];
        }

我猜这最糟糕的事情是一个循环,对于每个外部循环,我都必须重新运行所有logUnit。 但是不知道我还能怎么做。 也许有一种方法可以调用“选择时间等于[单位实时]的单位”之类的方法吗?

这里有一些危险信号。 悬念最少的是您正在扫描foo的所有子视图中的unit.view,这是一个O(n)操作,这在最内层的循环中确实很麻烦。

接下来,如果您按时间对两个数组进行排序,则实际上不必执行双循环来查找大小相同的事件。 看看如何在合并排序中完成。

如果那还不够好,请考虑在侧线程上进行所有比较工作,并仅将add子视图和视图创建过程分派回主线程。 它至少会使它看起来更快。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM