gitalk
gitalk copied to clipboard
重构荷兰政府那个非常有效的代码
重构荷兰政府那个非常有效的代码
荷兰政府最近被迫发布其DigiD数字认证iOS应用程序的源代码,好事者在review它的代码时,发现了一段非常有趣的函数:
还可以试试数组和map方式
var roundsArray = [...]string{
0: "☆☆☆☆☆☆☆☆☆☆",
1: "★☆☆☆☆☆☆☆☆☆",
2: "★★☆☆☆☆☆☆☆☆",
3: "★★★☆☆☆☆☆☆☆",
4: "★★★★☆☆☆☆☆☆",
5: "★★★★★☆☆☆☆☆",
6: "★★★★★★☆☆☆☆",
7: "★★★★★★★☆☆☆",
8: "★★★★★★★★☆☆",
9: "★★★★★★★★★☆",
}
func getPercentageRoundsArray(percentage float64) string {
if p := int(percentage * 10); p >= 0 && p < len(roundsArray) {
return roundsArray[p]
} else {
return "★★★★★★★★★★"
}
}
var roundsMap = map[int]string{
0: "☆☆☆☆☆☆☆☆☆☆",
1: "★☆☆☆☆☆☆☆☆☆",
2: "★★☆☆☆☆☆☆☆☆",
3: "★★★☆☆☆☆☆☆☆",
4: "★★★★☆☆☆☆☆☆",
5: "★★★★★☆☆☆☆☆",
6: "★★★★★★☆☆☆☆",
7: "★★★★★★★☆☆☆",
8: "★★★★★★★★☆☆",
9: "★★★★★★★★★☆",
}
func getPercentageRoundsMap(percentage float64) string {
if p, ok := roundsMap[int(percentage * 10)]; ok {
return p
} else {
return "★★★★★★★★★★"
}
}
结论还是有点区别,substring不是最快的。go 1.19
goos: windows
goarch: amd64
pkg: percent
cpu: Intel Xeon Processor (Skylake, IBRS)
BenchmarkPercentageRounds/original-8 185058242 6.480 ns/op
BenchmarkPercentageRounds/originalOpt-8 1000000000 0.2910 ns/op
BenchmarkPercentageRounds/switch-8 1000000000 0.8603 ns/op
BenchmarkPercentageRounds/tree-8 1000000000 0.2852 ns/op
BenchmarkPercentageRounds/substring-8 877959271 1.370 ns/op
BenchmarkPercentageRounds/concat-8 8593039 137.2 ns/op
BenchmarkPercentageRounds/array-8 1000000000 0.3037 ns/op
BenchmarkPercentageRounds/map-8 134443492 8.585 ns/op
PASS
ok percent 8.850s
goos: windows
goarch: amd64
pkg: go-rpc/tmp
cpu: Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz
BenchmarkPercentageRounds
BenchmarkPercentageRounds/original
BenchmarkPercentageRounds/original-8 141775195 8.333 ns/op
BenchmarkPercentageRounds/originalOpt
BenchmarkPercentageRounds/originalOpt-8 1000000000 0.3778ns/op
BenchmarkPercentageRounds/originalSwitch
BenchmarkPercentageRounds/originalSwitch-8 1000000000 1.091 ns/op
BenchmarkPercentageRounds/tree
BenchmarkPercentageRounds/tree-8 1000000000 0.3733ns/op
BenchmarkPercentageRounds/substring
BenchmarkPercentageRounds/substring-8 691862770 1.766 ns/op
BenchmarkPercentageRounds/concat
BenchmarkPercentageRounds/concat-8 12225598 97.08 ns/op
BenchmarkPercentageRounds/array
BenchmarkPercentageRounds/array-8 1000000000 0.3699ns/op
BenchmarkPercentageRounds/map
BenchmarkPercentageRounds/map-8 100000000 11.44 ns/op
PASS
不能使用percentage * 10的操作,会导致结果有误