internal/bench/index_bench_test.go

package bench

import (
	"bytes"
	"fmt"
	"strings"
	"testing"

	"mercemay.top/src/tilstream/internal/index/invert"
	"mercemay.top/src/tilstream/internal/index/serialize"
)

var indexBody = strings.Repeat(
	"The quick brown fox jumps over the lazy dog. "+
		"Go is a statically typed language designed at Google. ",
	50,
)

func buildBench(n int) *invert.Index {
	b := invert.NewBuilder()
	for i := 0; i < n; i++ {
		b.Add(invert.Doc{
			ID:    fmt.Sprintf("post-%d", i),
			Title: fmt.Sprintf("Post %d", i),
			Body:  indexBody,
			URL:   fmt.Sprintf("/%d.html", i),
			Tags:  []string{"bench"},
		})
	}
	return b.Build()
}

func BenchmarkBuildIndex(b *testing.B) {
	b.ReportAllocs()
	for i := 0; i < b.N; i++ {
		_ = buildBench(200)
	}
}

func BenchmarkSerializeLunr(b *testing.B) {
	idx := buildBench(200)
	s := serialize.NewSerializer()
	b.ReportAllocs()
	for i := 0; i < b.N; i++ {
		var buf bytes.Buffer
		if err := s.Write(&buf, idx); err != nil {
			b.Fatal(err)
		}
	}
}

func BenchmarkSearch(b *testing.B) {
	idx := buildBench(200)
	terms := []string{"quick", "brown", "language", "google"}
	b.ReportAllocs()
	for i := 0; i < b.N; i++ {
		_ = idx.Search(terms)
	}
}