Home > Backend Development > Golang > Empty Struct or Empty Interface: Which is the Better Map Value in Go?

Empty Struct or Empty Interface: Which is the Better Map Value in Go?

Susan Sarandon
Release: 2024-12-01 03:32:13
Original
467 people have browsed it

Empty Struct or Empty Interface: Which is the Better Map Value in Go?

Empty Interface vs. Empty Struct as Map Values

In Go, maps are used to store key-value pairs. The value type of a map can be any type, including interfaces or structs. While empty interfaces and empty structs can both be used to represent the absence of a value in a map, there are some key differences between the two.

Memory Usage

Empty structs have a fixed size of 0 bytes, regardless of the architecture. On the other hand, empty interfaces have a size of 8 bytes on 32-bit architectures and 16 bytes on 64-bit architectures. This is because empty interfaces store a pointer to the actual value, even if that value is nil.

The example code provided in the question demonstrates this difference:

package main

import (
    "fmt"
    "unsafe"
)

func main() {
    var s struct{}
    fmt.Println(unsafe.Sizeof(s))
    var i interface{}
    fmt.Println(unsafe.Sizeof(i))
    var b bool
    fmt.Println(unsafe.Sizeof(b))
}
Copy after login

Output (bytes for 32-bit architecture):

0
8
1
Copy after login

Output (bytes for 64-bit architecture):

0
16
1
Copy after login

As you can see, an empty struct has a memory overhead of 0 bytes, while an empty interface has an overhead of 8 bytes (32-bit) or 16 bytes (64-bit).

Performance

Using an empty struct is generally more efficient than using an empty interface in terms of performance. This is because the compiler can optimize operations involving empty structs more effectively.

Conclusion

Choosing between an empty interface and an empty struct as the value type of a map depends on the specific requirements of the application. If memory usage is a concern, an empty struct is the better choice. For performance reasons, an empty struct is also preferred. However, if the map is intended to be used with a variety of value types, an empty interface may be more appropriate.

The above is the detailed content of Empty Struct or Empty Interface: Which is the Better Map Value in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template