mirror of
https://github.com/rjNemo/underscore
synced 2026-06-06 10:36:43 +00:00
Replaces O(n²) bubble sort algorithm with O(n log n) slices.SortFunc from the standard library, delivering massive performance improvements. Performance improvements: - Large dataset (1000 items): 2,121,531 ns/op → 3,372 ns/op (629x faster!) - Small dataset (10 items): 199 ns/op → 178 ns/op (10% faster) - Time reduction: 99.84% for large datasets Resolves the TODO comment about replacing the simple algorithm. Also adds comprehensive benchmarks for both small and large datasets to track performance regressions. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
59 lines
1.1 KiB
Go
59 lines
1.1 KiB
Go
package underscore_test
|
|
|
|
import (
|
|
"testing"
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
|
|
u "github.com/rjNemo/underscore"
|
|
)
|
|
|
|
func Test_OrderBy_Asc(t *testing.T) {
|
|
set := u.Range(5, 0)
|
|
want := u.Range(0, 5)
|
|
|
|
result := u.OrderBy(set, func(left int, right int) bool {
|
|
return left > right
|
|
})
|
|
|
|
assert.Equal(t, want, result)
|
|
}
|
|
|
|
func Test_OrderBy_Desc(t *testing.T) {
|
|
set := u.Range(0, 5)
|
|
want := u.Range(5, 0)
|
|
|
|
result := u.OrderBy(set, func(left int, right int) bool {
|
|
return left < right
|
|
})
|
|
|
|
assert.Equal(t, want, result)
|
|
}
|
|
|
|
func BenchmarkOrderBy(b *testing.B) {
|
|
data := make([]int, 1000)
|
|
for i := range data {
|
|
data[i] = 1000 - i // Reverse order - worst case for bubble sort
|
|
}
|
|
|
|
b.ResetTimer()
|
|
for i := 0; i < b.N; i++ {
|
|
dataCopy := make([]int, len(data))
|
|
copy(dataCopy, data)
|
|
u.OrderBy(dataCopy, func(a, b int) bool { return a > b })
|
|
}
|
|
}
|
|
|
|
func BenchmarkOrderBySmall(b *testing.B) {
|
|
data := make([]int, 10)
|
|
for i := range data {
|
|
data[i] = 10 - i
|
|
}
|
|
|
|
b.ResetTimer()
|
|
for i := 0; i < b.N; i++ {
|
|
dataCopy := make([]int, len(data))
|
|
copy(dataCopy, data)
|
|
u.OrderBy(dataCopy, func(a, b int) bool { return a > b })
|
|
}
|
|
}
|