亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

哪個更好地獲取 Golang 字符串的最后一個 X 字符?

哪個更好地獲取 Golang 字符串的最后一個 X 字符?

Go
三國紛爭 2023-06-05 16:57:37
當我有字符串&ldquo;hogemogehogemogehogemoge 世界世界&rdquo;時,哪個代碼更適合避免內存分配以獲得最后一個符文?關于獲取 Golang String 的最后一個 X 字符也有類似的問題。如何獲取 Golang 字符串的最后 X 個字符?如果我只想獲得最后一個符文,而不需要任何額外的操作,我想確定哪個是首選。package mainimport (? ? "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)}
查看完整描述

1 回答

?
米琪卡哇伊

TA貢獻1998條經驗 獲得超6個贊

當性能和分配成為問題時,您應該運行基準測試。


首先讓我們修改您的函數以不打印而是返回結果:


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 倍多。它們都沒有進行任何分配,但這是由于編譯器優化(將 a 轉換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()是明顯的贏家。


查看完整回答
反對 回復 2023-06-05
  • 1 回答
  • 0 關注
  • 225 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號