Skip to content

Instantly share code, notes, and snippets.

@Integralist
Created October 24, 2025 17:25
Show Gist options
  • Select an option

  • Save Integralist/c2d769743b6755c671e57ffa21e102e4 to your computer and use it in GitHub Desktop.

Select an option

Save Integralist/c2d769743b6755c671e57ffa21e102e4 to your computer and use it in GitHub Desktop.
Go: Interface Boxing #perf

In Go, when you convert a concrete value (like a number or a struct) into an interface type, it's called interface boxing. This can sometimes cause performance problems because it can lead to hidden memory allocations on the heap, extra copying of data, and more work for the garbage collector. This is especially true for performance-critical code.

How it Works

An interface in Go is made up of two parts: a type descriptor and a data pointer. When you assign a value that isn't a pointer to an interface, Go might have to make a copy of that value on the heap. This can be slow and use a lot of memory, especially if you're working with large data structures.

The Problem

The main issue with interface boxing is the performance hit. For example, if you have a large struct and you add it to a slice of interfaces, each addition could cause a new memory allocation and a copy of the entire struct. This can make your program slower and use more memory than you might expect.

The Solution

To avoid these problems, you can often just use pointers instead of values when you're working with interfaces. When you assign a pointer to an interface, only the pointer is copied, which is much faster and uses less memory than copying a large struct.

How to Avoid it

If you need to avoid interface boxing for performance reasons, you can:

  • Use pointers when you assign values to interfaces.
  • Avoid using interfaces in code that needs to be as fast as possible.
  • Use type-specific containers (like []int or []string) instead of []interface{}.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment