maelvls dev blog

maelvls dev blog

Systems software engineer. I write mostly about Kubernetes and Go. About

09 Jul2020

Deepequal Is Slow

package main_test

import (
    "reflect"
    "testing"
)

type Status struct {
    Available bool
    Addresses []string
}

var (
    s1 = Status{
        Available: true,
        Addresses: []string{"87.35.9.18", "87.34.9.11", "some.tld.org"},
    }
    s2 = Status{
        Available: true,
        Addresses: []string{"87.35.9.18", "87.34.9.11", "some1.tld.org"},
    }
)

func BenchmarkDeepEqual(b *testing.B) {
    for i := 0; i < b.N; i++ {
        _ = reflect.DeepEqual(s1, s2)
    }
}

func BenchmarkFastEqual(b *testing.B) {
    for i := 0; i < b.N; i++ {
        _ = FastEqual(s1, s2)
    }
}

func FastEqual(s1 Status, s2 Status) bool {
    if len(s1.Addresses) != len(s2.Addresses) || s1.Available != s2.Available {
        return false
    }

    for i, s1addr := range s1.Addresses {
        if s1addr != s2.Addresses[i] {
            return false
        }
    }

    return true
}
% go test -bench .
BenchmarkDeepEqual-8   12256587        96.6 ns/op
BenchmarkFastEqual-8    135698862      8.75 ns/op
📝 Edit this page