英文:
Which is the most efficient nil value?
问题
嗨,在做一些练习时,我遇到了这个问题...假设你有一个容量为100,000的地图。哪个值是最有效的,可以在最短的时间内填满整个地图?
我自己进行了一些基准测试,尝试了我能想到的大多数类型,并得出了以下排名:
Benchmark_Struct-8 200 6010422 ns/op (struct{}{})
Benchmark_Byte-8 200 6167230 ns/op (byte = 0)
Benchmark_Int-8 200 6112927 ns/op (int8 = 0)
Benchmark_Bool-8 200 6117155 ns/op (bool = false)
示例函数:
func Struct() {
m := make(map[int]struct{}, 100000)
for i := 0; i < 100000; i++ {
m[i] = struct{}{}
}
}
正如你所看到的,最快的一个(大部分时间)是类型struct{}{}
- 空结构体。
- 但为什么在Go语言中是这样的呢?
- 是否有更快、更轻的nil或非nil值?
谢谢你的时间
英文:
Hi while doing some exercises I've came across this question...<br>
Lets say you have a map with the capacity of 100,000.<br>
Which value is the most efficient to fill the whole map in the least amount of time?
I've ran some benchmarks on my own trying out most of the types I could think of and the resulting top list is:
Benchmark_Struct-8 200 6010422 ns/op (struct{}{})
Benchmark_Byte-8 200 6167230 ns/op (byte = 0)
Benchmark_Int-8 200 6112927 ns/op (int8 = 0)
Benchmark_Bool-8 200 6117155 ns/op (bool = false)
Example function:
func Struct() {
m := make(map[int]struct{}, 100000)
for i := 0; i < 100000; i++ {
m[i] = struct{}{}
}
}
As you can see the fastest one (most of the time) is type struct{}{}
- empty struct.
- But why is this the case in go?
- Is there a faster/lighter nil or non-nil value?
<br>
- Thank you for your time
答案1
得分: 4
理论上,struct{}{}
应该是最高效的,因为它不需要内存。实际上,a) 在不同的Go版本、操作系统和系统架构下,结果可能会有所不同;b) 我无法想到任何情况下,最大化空值的执行时间效率是相关的。
英文:
Theoretically, struct{}{}
should be the most efficient because it requires no memory. In practice, a) results may vary between Go versions, operating systems, and system architectures; and b) I can't think of any case where maximizing the execution-time efficiency of empty values is relevant.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论