Why comparing two arrays with the comparing operator is way faster than using a loop in Go

Viewed 49

I would like to understand what Go is doing underneath when comparing two arrays like this:

if []int{1,2,3} < []int{1,2,4} {
  // something
}

because if I perform the same comparison using a loop, I'm way slower.

To demonstrate this also to myself, I've created these two tests:

package array

import (
    "strings"
    "testing"
)

var A = strings.Repeat("ADCIEHOBNOEFOHJWINMDUHFHWIHFID", 10000000) + "ADCIEHOBNOEFOHJWINMDUHFHWIHFID"
var B = strings.Repeat("ADCIEHOBNOEFOHJWINMDUHFHWIHFID", 10000000) + "_ADCIEHOBNOEFOHJWINMDUHFHWIHFID"

func BenchmarkLoopComparison(t *testing.B) {

    i := 0
    for i < len(A) && A[i] == B[i] {
        i++
    }

    if A[i] < B[i] {
        //
    } else {
        //
    }
}

func BenchmarkOperatorComparison(b *testing.B) {
    if A < B {
        //
    } else {
        //
    }
}

This was the outcome:

cpu: Intel(R) Core(TM) i5-3470 CPU @ 3.20GHz
BenchmarkLoopComparison-4       1000000000           0.2583 ns/op          0 B/op          0 allocs/op
PASS
ok      go-bench/array  4.879s

cpu: Intel(R) Core(TM) i5-3470 CPU @ 3.20GHz
BenchmarkOperatorComparison-4       1000000000           0.03792 ns/op         0 B/op          0 allocs/op
PASS
ok      go-bench/array  0.496s

From the bench, the results are obvious that the operator comparison is way faster than the loop comparison, so I would like to understand what Go is doing underneath to optimize the comparison.

0 Answers
Related