gpt4 book ai didi

swift - 如何快速处理大字符串?

转载 作者:搜寻专家 更新时间:2023-11-01 05:52:05 24 4
gpt4 key购买 nike

我有这段代码,但它需要很长时间才能快速执行?每次迭代需要 1 秒来执行,为什么?

执行该循环时的 CPU 百分比为 97-98%,能源影响很高

这是代码

     var braces:Int = 1;
var i:Int = startIndex;
let jsFileChars = Array(javascriptFile);
while(i < javascriptFile.count){ //count:1240265
if (braces == 0) {
break;
}
if (jsFileChars[i] == "{"){
braces = braces+1;
}else if (jsFileChars[i] == "}"){
braces = braces-1;
}
i = i+1;
}

这个循环的迭代速度非常慢,为什么?

最佳答案

循环很慢,因为确定 Swift stringcount 是一个O(N) 操作,其中 N 是字符串中的字符数。另见 Counting Characters在“The Swift Programming Language”中:

NOTE

Extended grapheme clusters can be composed of multiple Unicode scalars. This means that different characters—and different representations of the same character—can require different amounts of memory to store. Because of this, characters in Swift don’t each take up the same amount of memory within a string’s representation. As a result, the number of characters in a string can’t be calculated without iterating through the string to determine its extended grapheme cluster boundaries. ...

jsFileChars.count 替换 javascriptFile.count 应该已经提高性能,因为数组的长度由常数时间。

更好的做法是直接遍历字符,而无需创建数组:

var braces = 1
for char in javascriptFile {
if char == "{" {
braces += 1
} else if char == "}" {
braces -= 1
}
}

迭代 UTF-16 View 更快,因为是 Swift 字符串(当前)用作内部存储的内容:

let openingBrace = "{".utf16.first!
let closingBrace = "}".utf16.first!

var braces = 1
for char in javascriptFile.utf16 {
if char == openingBrace {
braces += 1
} else if char == closingBrace {
braces -= 1
}
}

关于swift - 如何快速处理大字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49049443/

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