Home >Backend Development >Golang >Empty Struct vs. Empty Interface in Go Maps: Which is More Memory Efficient?

Empty Struct vs. Empty Interface in Go Maps: Which is More Memory Efficient?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-18 19:34:10949browse

Empty Struct vs. Empty Interface in Go Maps: Which is More Memory Efficient?

Memory Efficiency Considerations: Empty Interface vs. Empty Struct in Maps

One may wonder about the distinction between using an empty interface and an empty struct as the value in a map when seeking to emulate a set in Go. Let's delve into the memory usage differences that arise from this choice.

Consider the following types:

type MyType uint8

To simulate a set, one might utilize the following construct:

map[MyType]interface{}

However, it's worth noting that one can also employ an empty struct instead:

map[MyType]struct{}

The primary benefit of using an empty struct is its reduced memory usage compared to an empty interface. The following example 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))
}

Output (bytes for 32-bit architecture):

0
8

Output (bytes for 64-bit architecture):

0
16

As the results indicate, an empty struct occupies zero bytes of memory, while an empty interface consumes either 8 or 16 bytes depending on the architecture.

Therefore, if memory efficiency is a crucial consideration, opting for an empty struct as the value in your map is a wise choice.

The above is the detailed content of Empty Struct vs. Empty Interface in Go Maps: Which is More Memory Efficient?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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