gpt4 book ai didi

arrays - 将字符串拆分为数组 string.components(separtedBy : ",") consumes more time

转载 作者:行者123 更新时间:2023-11-28 07:20:41 25 4
gpt4 key购买 nike

我有一个包含 18000 行城市名称的文本文件。每行都有城市名称、州、纬度、经度等。下面是执行此操作的函数,如果我不实现 string.components(separtedBy: ", ") 加载函数非常快但是实现它需要时间,这会使我的 UI 卡住。正确的做法是什么? string.components(separtedBy: ", ") 有这么贵吗?

我分析了该应用,这一行在整个函数中花费了 2.09 秒中的 string.components(separtedBy: ", ") 1.45 秒。

func readCitiesFromCountry(country: String) -> [String] {
var cityArray: [String] = []
var flag = true
var returnedCitiesList: [String] = []

if let path = Bundle.main.path(forResource: country, ofType: "txt") {
guard let streamReader = StreamReader(path: path) else {fatalError()}
defer {
streamReader.close()
}
while flag {
if let nextLine = streamReader.nextLine() {
cityArray = nextLine.components(separatedBy: ",") // this is the line taking a lot of time, without this function runs pretty fast
if (country == "USA") {
returnedCitiesList.append("\(cityArray[0]) , \(cityArray[1]) , \(cityArray[2])")
} else {
returnedCitiesList.append("\(cityArray[0]) , \(cityArray[1])")
}
//returnedCitiesList.append(nextLine)
} else {
flag = false
}
}
} else {
fatalError()
}

return returnedCitiesList
}

代码中使用的StreamReader可以在这里找到。它有助于逐行读取文件 Read a file/URL line-by-line in Swift

这道题不是关于如何把字符串拆分成数组Split a String into an array in Swift? ,而不是为什么拆分在给定函数中花费更多时间。

最佳答案

NSString.components(separatedBy:) 返回一个[String],它要求从原始字符串复制所有片段的内容,并粘贴到新分配的字符串中。这会减慢速度。

您可以通过将这项工作放在后台线程上来解决问题(UI 卡住),但这只会将问题归咎于错误(低效复制仍然存在),并使事情复杂化(异步代码从来都不是有趣的)。

相反,您应该考虑使用 String.split(separator:maxSplits:omittingEmptySubsequences:) ,它返回 [Substring]。每个 Substring 只是原始字符串内存的一个 View ,它存储相关范围,因此您只能看到由 Substring 建模的 String 部分。此处发生的唯一内存分配是针对数组的。

希望这足以将您的代码加速到可接受的水平。如果不是,您应该结合这两种解决方案,并在线程外使用 split

关于arrays - 将字符串拆分为数组 string.components(separtedBy : ",") consumes more time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58207557/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com