查找行数最快的方法?

Rob*_*ert 5 string performance go

我现在正在使用的是:

numlines := strings.Count(editor.Text(), "\n")
fmt.Print(strconv.Itoa(numlines))
message.SetText(strconv.Itoa(numlines))
Run Code Online (Sandbox Code Playgroud)

每当更新文本框时,就会运行该命令。最像这样的方式是什么?

icz*_*cza 5

那完全没问题。但不要忘记,如果最后一个字符不是换行符,则必须在出现次数上加 1,因为这将是行数(最后一行可能不会以换行符结尾)。

我们可能会认为,由于您计算的子字符串只是一个字符(单个rune),我们可以创建一个自定义解决方案,只计算这个单个字符的出现次数(而不是计算子字符串)。它可能看起来像这样:

func countRune(s string, r rune) int {
    count := 0
    for _, c := range s {
        if c == r {
            count++
        }
    }
    return count
}
Run Code Online (Sandbox Code Playgroud)

for range一个string值上的A迭代它的runes。)

并对其进行测试(在Go Playground上尝试):

fmt.Println(countRune("asdf\nasdf\nasdf\n", '\n')) // Prints 3
Run Code Online (Sandbox Code Playgroud)

实际上,这不会更快地计算换行符,因为它是byteUTF-8 编码中的单个字符,并且strings.Count()已经针对计算子字符串长度为 1 的子字符串进行了优化:

// Count counts the number of non-overlapping instances of substr in s.
// If substr is an empty string, Count returns 1 + the number of Unicode code points in s.
func Count(s, substr string) int {
    if len(substr) == 1 && cpu.X86.HasPOPCNT {
        return countByte(s, byte(substr[0]))
    }
    return countGeneric(s, substr)
}

func countByte(s string, c byte) int // ../runtime/asm_amd64.s
Run Code Online (Sandbox Code Playgroud)

可以提高此操作(计数行)的性能的是,如果您可以访问编辑器的“内部”字节或符文数组,则不必调用其Text()方法,该方法创建并返回其内容的副本.