gpt4 book ai didi

performance - 根据前一个 slice 创建一个新 slice ,没有给定值

转载 作者:行者123 更新时间:2023-12-04 03:25:38 25 4
gpt4 key购买 nike

我有一段字符串。我需要完成的是在不知道索引的情况下从 slice 中删除一个值。我认为这是最简单的方法:


// Return a slice that is the original without the given string
func newSliceWithout(s []string, without string) []string {
l := []string{}
for _, elem := range s {
if elem != without {
l = append(l, elem)
}
}
return l
}

但是,在执行基准测试时,我得到了相当高的值(正如预期的那样),所以我想知道是否有更快/更有效的方法来做到这一点?

最佳答案

一步分配一个大的返回 slice (由输入 slice 估计),不使用append()而是分配给单个元素:

func newSliceWithout(s []string, without string) []string {
l, i := make([]string, len(s)), 0
for _, elem := range s {
if elem != without {
l[i] = elem
i++
}
}
return l[:i]
}

测试它:

x := newSliceWithout([]string{"a", "b", "a", "c"}, "a")
fmt.Println(x)

哪些输出(在 Go Playground 上尝试):

[b c]

基准

func BenchmarkNewSliceWithoutOrig(b *testing.B) {
for n := 0; n < b.N; n++ {
newSliceWithoutOrig([]string{"a", "b", "a", "c"}, "a")
}
}

func BenchmarkNewSliceWithout(b *testing.B) {
for n := 0; n < b.N; n++ {
newSliceWithout([]string{"a", "b", "a", "c"}, "a")

}
}

结果:

BenchmarkNewSliceWithoutOrig-8    7416729   139.0 ns/op   48 B/op  2 allocs/op
BenchmarkNewSliceWithout-8 13280971 103.4 ns/op 64 B/op 1 allocs/op

如果我们使用更大的 slice :

var s = []string{"a", "b", "x", "y", "z", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "c"}

然后基准测试结果:

BenchmarkNewSliceWithoutOrig-8   2253637   566.8 ns/op   496 B/op    5 allocs/op
BenchmarkNewSliceWithout-8 5160316 224.3 ns/op 256 B/op 1 allocs/op

关于performance - 根据前一个 slice 创建一个新 slice ,没有给定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67660392/

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