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
Release: 2024-12-18 19:34:10
Original
955 people have browsed it

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
Copy after login

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

map[MyType]interface{}
Copy after login

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

map[MyType]struct{}
Copy after login

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))
}
Copy after login

Output (bytes for 32-bit architecture):

0
8
Copy after login

Output (bytes for 64-bit architecture):

0
16
Copy after login

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!

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