哪个是最高效的空值?

huangapple go评论68阅读模式
英文:

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 &lt; 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.

huangapple
  • 本文由 发表于 2017年6月21日 01:22:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/44659422.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定