如何在Swift中更有效地将对象数组划分为子数组?

时间:2018-01-18 04:08:06

标签: algorithm optimization performance

我有一个Swift应用程序,以下for循环需要大约一秒钟才能完成。有没有办法改善表现?我可以使用3种for方法替换filter循环,但我怀疑它会有所帮助。

// metrics.count == 10000
var metricsByStatus: Dictionary<String, Array<HKQuantitySample>> = ["low": [], "high": [], "normal": []]

// HKQuantitySample.status:
func status(low: Double, high: Double) -> String {
    if value < low {
        return "low"
    } else if value > high {
        return "high"
    } else {
        return "normal"
    }
}

// This is taking 1 second, 100% CPU
for metric in metrics {
  metricsByStatus[metric.status(low: limits["low"], high: limits["high"])].append(metric)
}

1 个答案:

答案 0 :(得分:0)

用枚举值替换“低”,“中”,“高”。

在循环之前提取限制[低],限制[高]一次。

配置现有代码。你会发现它花费大部分时间来比较字符串。

仅测量发布版本中的性能,而不是调试版本。

我发现[String: [HKQuantitySample]]Dictionary<String, Array<HKQuantitySample>>更具可读性。

相关问题