Allocated slices with fixed capacity vs arrays

I’m curious about the performance hit when I use a slice that’s allocated to a fixed capacity vs a fixed array.

I like to use slices that are allocated to a fixed capacity and then use the convenience of append to populate that slice…

slc := make([]uint, 0, 8)//slice will always need to be 8 elements
slc = append(slc, 6)//append data 8 times

Is the performance hit(in my case) insignificant?

Note: I know the capacity of a slice is not fixed but I’m not exceeding that limit in my code.

Hi G4143, how are you?
I have created a file with following script “sliceBenchmark.go”:

package main

const SLICE_CAPACITY = 8

func main() {
	fixedArray()
	withCapacity()
	withoutCapacity()
}

func fixedArray() {
	var slc [SLICE_CAPACITY]uint
	for i := 0; i < SLICE_CAPACITY; i++ {
		slc[i] = 6
	}
}
func withCapacity() {
	slc := make([]uint, 0, SLICE_CAPACITY)
	for i := 0; i < SLICE_CAPACITY; i++ {
		slc = append(slc, 6)
	}
}
func withoutCapacity() {
	slc := []uint{}
	for i := 0; i < SLICE_CAPACITY; i++ {
		slc = append(slc, 6)
	}
}

And another file with benchmarks “sliceBenchmark_test.go”:

package main

import (
	"testing"
)

func BenchmarkWithCapacity(b *testing.B) {
        for n := 0; n < b.N; n++ {
                withCapacity()
        }
}

func BenchmarkWithoutCapacity(b *testing.B) {
        for n := 0; n < b.N; n++ {
                withoutCapacity()
        }
}

func BenchmarkFixedArray(b *testing.B) {
        for n := 0; n < b.N; n++ {
                fixedArray()
        }
}

With my laptop, I have got the following results:
|BenchmarkWithCapacity-4 |210583917| 5.995 ns/op|
|BenchmarkWithoutCapacity-4 |10043202| 113.6 ns/op|
|BenchmarkFixedArray-4 |381437634| 3.104 ns/op|

The function with capacity is 20 times faster than without capacity.
And fixed array is faster than the slice with capacity :slight_smile:

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.