Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/contains iterate by index #428

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

lennon-guan
Copy link

Refactor Contains function to improve performance by using index iteration over collection

@lennon-guan
Copy link
Author

// Benchmark Code & Result
package lo

import "testing"

func oldContains[T comparable](collection []T, element T) bool {
	for _, item := range collection {
		if item == element {
			return true
		}
	}
	return false
}

type containsTestStruct struct {
	A, B, C, D int
	E, F       string
}

var (
	containsInts    = []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
	containsStrings = []string{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}
	containsStructs = []containsTestStruct{{}, {}, {}, {}, {}, {}, {}, {}, {}, {A: 1}}
)

func doBenchmark[T comparable](b *testing.B, collection []T, fn func([]T, T) bool) {
	element := collection[len(collection)-1]
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		fn(collection, element)
	}
}

func BenchmarkOldContainsInt(b *testing.B) {
	doBenchmark(b, containsInts, oldContains[int])
}

func BenchmarkContainsInt(b *testing.B) {
	doBenchmark(b, containsInts, Contains[int])
}

func BenchmarkOldContainsString(b *testing.B) {
	doBenchmark(b, containsStrings, oldContains[string])
}

func BenchmarkContainsString(b *testing.B) {
	doBenchmark(b, containsStrings, Contains[string])
}

func BenchmarkOldContainsStruct(b *testing.B) {
	doBenchmark(b, containsStructs, oldContains[containsTestStruct])
}

func BenchmarkContainsStruct(b *testing.B) {
	doBenchmark(b, containsStructs, Contains[containsTestStruct])
}

//result

goos: windows
goarch: amd64
pkg: github.com/samber/lo
cpu: AMD Ryzen 7 5800H with Radeon Graphics         
BenchmarkOldContainsInt-16       	235373313	         5.196 ns/op	       0 B/op	       0 allocs/op
BenchmarkContainsInt-16          	232900494	         5.139 ns/op	       0 B/op	       0 allocs/op
BenchmarkOldContainsString-16    	127452003	         9.454 ns/op	       0 B/op	       0 allocs/op
BenchmarkContainsString-16       	174648490	         6.784 ns/op	       0 B/op	       0 allocs/op
BenchmarkOldContainsStruct-16    	20864157	        54.47 ns/op	       0 B/op	       0 allocs/op
BenchmarkContainsStruct-16       	26957204	        44.76 ns/op	       0 B/op	       0 allocs/op
PASS
ok  	github.com/samber/lo	10.777s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant