Skip to content

perf(builtin): avoid quadratic string scans in uniq - #1007

Merged
antonmedv merged 1 commit into
expr-lang:masterfrom
TheNetherWatcher:perf/uniq-strings
Nov 22, 2026
Merged

antonmedv merged 1 commit into
expr-lang:masterfrom
TheNetherWatcher:perf/uniq-strings

Conversation

@TheNetherWatcher

Copy link
Copy Markdown
Contributor

uniq compared each element against every value already kept, and re-boxed v.Index(i).Interface() on every comparison. For lists with many distinct strings this is quadratic work plus repeated allocations.

This PR:

  • reads each element once instead of once per comparison
  • once 16 distinct values have been collected, builds a map[string]struct{} index (seeded from the values kept so far) and uses it for string elements
  • keeps the existing runtime.Equal scan for all non-string values and for small results

Output and first-occurrence order are unchanged. runtime.Equal only treats a string as equal to another string (named string types fall through to reflect.DeepEqual, which also requires identical types), so a string-keyed index cannot change which elements are dropped.

Benchmark

expr.Run with a pre-compiled program, Apple M4 Pro, Go 1.27, median of 7:

Workload Items Before After Speedup
join(uniq(labels), ",") 32 5.51 µs 2.17 µs 2.5x
join(uniq(labels), ",") 128 75.9 µs 7.43 µs 10.2x
join(uniq(labels), ",") 512 1193 µs 27.3 µs 43.7x
join(uniq(map(orders, .CustomerEmail)), ",") 128 38.6 µs 10.6 µs 3.7x
join(uniq(map(orders, .CustomerEmail)), ",") 512 525 µs 39.2 µs 13.4x
all-identical control 8–512 ~0.98x

Lists with very few distinct values never reach the index threshold and stay within ~2% of before.

Tests

Added tests covering the index path (more than 16 distinct strings, mixed string / non-string values, ordering). go test ./... passes.

@antonmedv
antonmedv merged commit f14b1e3 into expr-lang:master Nov 22, 2026
30 of 31 checks passed
antonmedv added a commit that referenced this pull request Nov 25, 2026
Extend the string index from #1007 to integer and float values, keyed the same way runtime.Equal compares them. uniq(1..999999) drops from hours to ~200ms.
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.

2 participants