【问题标题】:Swift App Takes ~6 Minutes To BuildSwift App 需要大约 6 分钟的时间来构建
【发布时间】:2015-06-04 07:50:23
【问题描述】:

我有一个 Swift 应用程序,其中包含大约 10 万个字符串的数组。数组看起来像这样:

let strings: [String] = [
    "a",
    "as",
    // 99,998 elements later...
    "zebra"
]

在 iOS 模拟器中构建和运行应用程序需要将近 6 分钟。我已将缓慢的构建时间与在项目中包含此数组隔离开来。一旦建成,随后的启动速度非常快(直到我必须再次构建)。我可以做些什么来加快构建过程?

【问题讨论】:

  • 将数据放入数据库。您真的需要一次在内存中存储 100,000 个字符串吗?
  • 对于上下文,我正在过滤(整个)数组 1) 用于具有所需字符数(例如 4 或 7)的字符串和 2) 用于所有字符都包含在预选字符串中的字符串(例如“生命线”,其中“文件”将匹配,但“叶子”或“生命线”不会)。我真的很想避免数据库的额外复杂性,尽管我知道这会如何减少编译时间。
  • 所有这些都可以使用数据库来完成。
  • 我不怀疑 :) 还有其他建议吗?例如,从纯文本文件中读取不会减慢编译时间。也就是说,一旦构建了应用程序,它可能会变得非常低效。
  • 将所有 100,000 个单词加载到内存中的任何方法都是一个坏主意。

标签: ios arrays performance swift compiler-optimization


【解决方案1】:

根据上面的 cmets,对我来说最好的解决方案是使用文本文件。数据库也可以工作,尽管在这种情况下它会增加不必要的复杂性。文本文件如下所示:

a
as
...
zebra

使用来自this SO postthe StreamReader gist 读取文件。这样做的代码如下所示:

if let aStreamReader = StreamReader(path: "/path/to/file") {
    for word in aStreamReader {
        // This is where I'm testing the following conditions:
        // 1) Does the word have a specific number of characters (e.g. 4 or 7)?
        // 2) Do all the characters in the word exist in a stored string?
        // e.g "lifeline", where "file" would match, but "lifelines" wouldn't.
        // This code is only here for context.
        if contains(characterCountsToMatch, countElements(word)) {
            if stringToMatch.containsCharsInString(word) {
                matchingWords.append(word)
            }
        }
    }
}

生成的matchingWords 数组只包含必要的元素——在我的例子中大约有 600 个(不是~100k 个元素!)。该应用程序现在可以立即编译。从文件读取并将匹配项附加到 matchingWords 数组大约需要 5 秒,这可以满足我的需要,但如果需要可以进一步优化。

【讨论】:

    猜你喜欢
    • 2017-08-15
    • 1970-01-01
    • 1970-01-01
    • 2019-08-03
    • 2016-10-07
    • 1970-01-01
    • 2018-08-17
    • 1970-01-01
    • 2022-01-02
    相关资源
    最近更新 更多