performance: Improve prefix_sort.

We only convert the query to lowercase outside the
loop for an Nx speedup, where N = number of items.

And then we use startsWith instead of indexOf, which
means we don't senselessly search entire strings
for matches.

(We've had startsWith polyfills for a while now.)

Unfortunately, unless a string start with the
exact casing of the query, we still create an
entire lowercase copy of the string for the case
insensitive match.  For the English use case
(and many other languages), we could further
optimize this by slicing the string before
converting it to lowercase.

Unfortunately, you have languages like German
with the straße/STRASSE problem.  It's not clear
to me how we handle them with the current code,
but I don't want to break that yet.
This commit is contained in:
Steve Howell
2020-01-28 13:25:08 +00:00
parent 10e75e6df5
commit d3e961e179

View File

@@ -241,13 +241,14 @@ exports.prefix_sort = function (query, objs, get_item) {
const beginswithCaseSensitive = [];
const beginswithCaseInsensitive = [];
const noMatch = [];
const lowerQuery = query.toLowerCase();
for (const obj of objs) {
const item = get_item(obj);
if (item.indexOf(query) === 0) {
if (item.startsWith(query)) {
beginswithCaseSensitive.push(obj);
} else if (item.toLowerCase().indexOf(query.toLowerCase()) === 0) {
} else if (item.toLowerCase().startsWith(lowerQuery)) {
beginswithCaseInsensitive.push(obj);
} else {
noMatch.push(obj);