gpt4 book ai didi

string - 哪个更好地获取 Golang 字符串的最后一个 X 字符?

转载 作者:IT王子 更新时间:2023-10-29 01:22:54 30 4
gpt4 key购买 nike

当我有字符串 "hogemogehogemogehogemoge 世界世界世界"时,哪个代码可以更好地获得最后一个 rune 并避免内存分配?

关于获取Golang String的最后一个X字符有类似的问题。

How to get the last X Characters of a Golang String?

如果我只想获得最后一个 rune ,而不需要任何额外的操作,我想确定哪个是首选。

package main

import (
"fmt"
"unicode/utf8"
)

func main() {
// which is more better for memory allocation?
s := "hogemogehogemogehogemoge世界世界世界a"
getLastRune(s, 3)
getLastRune2(s, 3)
}

func getLastRune(s string, c int) {
// DecodeLastRuneInString
j := len(s)
for i := 0; i < c && j > 0; i++ {
_, size := utf8.DecodeLastRuneInString(s[:j])
j -= size
}
lastByRune := s[j:]
fmt.Println(lastByRune)
}

func getLastRune2(s string, c int) {
// string -> []rune
r := []rune(s)
lastByRune := string(r[len(r)-c:])
fmt.Println(lastByRune)
}

世界a

世界a

最佳答案

每当出现性能和分配问题时,您都应该运行基准测试。

首先让我们修改您的函数,使其不打印而是返回结果:

func getLastRune(s string, c int) string {
j := len(s)
for i := 0; i < c && j > 0; i++ {
_, size := utf8.DecodeLastRuneInString(s[:j])
j -= size
}
return s[j:]
}

func getLastRune2(s string, c int) string {
r := []rune(s)
if c > len(r) {
c = len(r)
}
return string(r[len(r)-c:])
}

基准函数:

var s = "hogemogehogemogehogemoge世界世界世界a"

func BenchmarkGetLastRune(b *testing.B) {
for i := 0; i < b.N; i++ {
getLastRune(s, 3)
}
}

func BenchmarkGetLastRune2(b *testing.B) {
for i := 0; i < b.N; i++ {
getLastRune2(s, 3)
}
}

运行它们:

go test -bench . -benchmem

结果:

BenchmarkGetLastRune-4     30000000     36.9 ns/op     0 B/op    0 allocs/op
BenchmarkGetLastRune2-4 10000000 165 ns/op 0 B/op 0 allocs/op

getLastRune()快 4 倍。它们都没有进行任何分配,但这是由于编译器优化(将 string 转换为 []rune 并返回通常需要分配)。

如果我们在禁用优化的情况下运行基准测试:

go test -gcflags '-N -l' -bench . -benchmem

结果:

BenchmarkGetLastRune-4     30000000    46.2 ns/op      0 B/op    0 allocs/op
BenchmarkGetLastRune2-4 10000000 197 ns/op 16 B/op 1 allocs/op

编译器优化与否,getLastRune() 是明显的赢家。

关于string - 哪个更好地获取 Golang 字符串的最后一个 X 字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54475723/

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