2

新的 exp/slices 包大部分比较函数都比较慢

 2 years ago
source link: https://www.v2ex.com/t/822599
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

V2EX  ›  Go 编程语言

新的 exp/slices 包大部分比较函数都比较慢

  Kisesy · 21 小时 3 分钟前 · 315 次点击
package main

import (
	"runtime"
	"testing"

	"golang.org/x/exp/slices"
)

var (
	aa = make([]runtime.MemStats, 1)
	bb = make([]runtime.MemStats, 1)
)

func Benchmark1(b *testing.B) {
	for i := 0; i < b.N; i++ {
		slices.Equal(aa, bb)
	}
}

func Benchmark2(b *testing.B) {
	for i := 0; i < b.N; i++ {
		Equal(aa, bb)
	}
}

func Benchmark3(b *testing.B) {
	for i := 0; i < b.N; i++ {
		Equal2(aa, bb)
	}
}

func Equal[E comparable](s1, s2 []E) bool {
	if len(s1) != len(s2) {
		return false
	}
	for i := range s1 {
		if s1[i] != s2[i] {
			return false
		}
	}
	return true
}

func Equal2[E comparable](s1, s2 []E) bool {
	if len(s1) != len(s2) {
		return false
	}
	for i := 0; i < len(s1); i++ {
		if s1[i] != s2[i] {
			return false
		}
	}
	return true
}

/*
cpu: AMD Ryzen 5 2500U with Radeon Vega Mobile Gfx
Benchmark1-8   	  638925	      1652 ns/op	       0 B/op	       0 allocs/op
Benchmark2-8   	 5131083	       221.2 ns/op	       0 B/op	       0 allocs/op
Benchmark3-8   	 5423184	       229.6 ns/op	       0 B/op	       0 allocs/op
*/

原因就是代码使用 range 来带值遍历, 这样会进行复制数据
这个包里不少函数都是这样的, 有兄弟愿意的话可以去官方提交代码或提个意见


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK