From 1a9e509ee24772c601b0e165333304d32a112fb1 Mon Sep 17 00:00:00 2001 From: CharlesKWON Date: Fri, 1 May 2026 08:03:13 +0900 Subject: [PATCH] perf(rtl): SORT TO swaps insertion sort for sort.SliceStable (Wave 4) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Drop the toy O(n²) insertion-sort that __dbSort had been using and delegate to the stdlib's sort.SliceStable. Reasoning: SORT TO is an operation a user reaches for *because* their dataset is too big to just iterate manually — interactive DBFs routinely have 10k–1M rows, which the old impl would chew on for minutes to hours. SliceStable gives O(n log n) and preserves the original-input ordering for equal keys, which is what the previous implementation also tried to do. The function signature is unchanged (`stableSort(rows, less)`), so all the multi-key / /D / /C dispatch logic from earlier waves keeps working unmodified. Gates green: go test ./... : PASS FiveSql2 SQL:1999 : 43/43 Harbour compat : 56/56 Co-Authored-By: Claude Opus 4.7 (1M context) --- hbrtl/database.go | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/hbrtl/database.go b/hbrtl/database.go index b8b9949..4bdce44 100644 --- a/hbrtl/database.go +++ b/hbrtl/database.go @@ -10,6 +10,7 @@ package hbrtl import ( "fmt" "os" + "sort" "strings" "five/hbrt" @@ -1914,14 +1915,12 @@ func rtlDbUpdate(t *hbrt.Thread) { t.RetBool(true) } -// stableSort is a tiny insertion sort for small N (typical DBF SORT -// targets are interactive datasets). Avoids a sort import dependency. +// stableSort sorts rows in place via the stdlib's `sort.SliceStable` +// — O(n log n) with stable ordering preserved for equal keys. The +// previous insertion-sort implementation degraded to O(n²) and was +// unusable for DBFs over a few thousand rows. func stableSort(rows [][]hbrt.Value, less func(i, j int) bool) { - for i := 1; i < len(rows); i++ { - for j := i; j > 0 && less(j, j-1); j-- { - rows[j], rows[j-1] = rows[j-1], rows[j] - } - } + sort.SliceStable(rows, less) } // --- DBSETFILTER / DBCLEARFILTER / DBFILTER ---