Skip to content

How to Improve Slice Performance in Go

If you are initiating a new slice and you know how many items you will put into it, then use the make() function:

data := make([]int, 0, 5) // len(b)=0, cap(b)=5

this snippet will improve your performance significantly, Let’s see an example:

package main

import "fmt"

func main() {
	// You recived a slice and it has a length
	items := getDataFromDb()

	// You know that you need a slice with the capacity of len(items)
	// Call the make() function to create a slice
	// In this way there is no need to allocate new space on appending
	// allocation process is expensive
	squareItems := make([]int, 0, len(items))

	// Use the new slice with the better performance
	for _, item := range items {
		squareItems = append(squareItems, item*item)


func getDataFromDb() []int {
	return []int{
		1, 2, 3, 4, 5,

1 thought on “How to Improve Slice Performance in Go”

  1. Pingback: Golang Merge Slices Unique – Remove Duplicates – Code Paste

Leave a Reply

Your email address will not be published. Required fields are marked *