git » firstones » commit 4eb65ed

ipa: Add benchmark for SmartWordToGlyphs

author Alberto Bertogli
2026-07-26 17:36:00 UTC
committer Alberto Bertogli
2026-07-26 19:07:05 UTC
parent a582a81cf0b49f692eac8b72f5202e2f50d3b06e

ipa: Add benchmark for SmartWordToGlyphs

The SmartWordToGlyphs function abstracts away the word -> IPA
conversion.

This patch adds a benchmark to measure its performance, in anticipation
for future changes.

ipa_test.go +51 -0

diff --git a/ipa_test.go b/ipa_test.go
index 7282402..1949788 100644
--- a/ipa_test.go
+++ b/ipa_test.go
@@ -1,6 +1,10 @@
 package main
 
 import (
+	"bytes"
+	"maps"
+	"os"
+	"slices"
 	"strings"
 	"testing"
 
@@ -212,3 +216,50 @@ func TestLookups(t *testing.T) {
 		}
 	}
 }
+
+// sampleWords takes n words spread evenly over the given dictionary file.
+//
+// We read the file directly, instead of going through the dictionaries,
+// for two reasons: map iteration order is random, and we want the same words
+// on every run; and it keeps the benchmark independent of how the
+// dictionaries are embedded and parsed, so results remain comparable across
+// changes to that.
+func sampleWords(b *testing.B, fname string, n int) []string {
+	contents, err := os.ReadFile(fname)
+	if err != nil {
+		b.Fatal(err)
+	}
+
+	every := max(bytes.Count(contents, []byte("\n"))/n, 1)
+	words := []string{}
+	i := 0
+	for line := range strings.Lines(string(contents)) {
+		if i%every == 0 {
+			if w, _, ok := strings.Cut(line, "\t"); ok {
+				words = append(words, w)
+			}
+		}
+		i++
+	}
+	return words
+}
+
+// BenchmarkSmartWordToGlyphs measures the word -> glyphs conversion.
+// Note the set of words is small enough to stay in cache, so this measures the
+// conversion itself, and not the cost of reaching into a cold dictionary.
+func BenchmarkSmartWordToGlyphs(b *testing.B) {
+	// A varied mix, with no single source dominating: the character names,
+	// and a sample of each dictionary. Both languages are represented, so we
+	// cover the words that are found on the first try, as well as the ones
+	// that need a failed lookup in the other dictionary first.
+	words := slices.Sorted(maps.Keys(namesIPA))
+	for _, f := range []string{"ipa/en_US.txt", "ipa/es_MX.txt"} {
+		words = append(words, sampleWords(b, f, 100)...)
+	}
+
+	i := 0
+	for b.Loop() {
+		SmartWordToGlyphs(words[i%len(words)])
+		i++
+	}
+}