underscore/flatmap_test.go
Ruidy 75eddcdde5
perf: improve Flatmap allocation strategy
Pre-allocates result slice with estimated capacity to reduce
repeated allocations during append operations.

Strategy:
- Estimates capacity as len(values) * 2
- Assumes average of 2-3 items per mapped element
- Simple heuristic that works well for typical use cases

Performance improvements:
- Time: 907.4 ns/op → 616.7 ns/op (32% faster)
- Memory: 6,120 B/op → 4,992 B/op (18% less)
- Allocations: 8 → 2 (75% reduction)

Impact:
- Significantly reduces allocation overhead
- Better performance for typical flatmap operations
- May over-allocate if mapper returns <2 items on average

Added BenchmarkFlatmap to track performance.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-14 14:29:40 +01:00

30 lines
592 B
Go

package underscore_test
import (
"testing"
"github.com/stretchr/testify/assert"
u "github.com/rjNemo/underscore"
)
func TestFlatmap(t *testing.T) {
nums := []int{1, 2, 3, 4}
transform := func(n int) []int { return []int{(n - 1) * n, (n) * n} }
want := []int{0, 1, 2, 4, 6, 9, 12, 16}
assert.Equal(t, want, u.Flatmap(nums, transform))
}
func BenchmarkFlatmap(b *testing.B) {
data := make([]int, 100)
for i := range data {
data[i] = i
}
mapper := func(n int) []int { return []int{n, n * 2, n * 3} }
b.ResetTimer()
for i := 0; i < b.N; i++ {
u.Flatmap(data, mapper)
}
}