๐Ÿ“š General & Other

Prefix Matching Is the Cheapest Filter Available

keeps lines starting with that path. Prefix matching is the most efficient string filter there is, and it has a couple of properties worth exploiting.

grep '^/blog/' keeps lines starting with that path. Prefix matching is the most efficient string filter there is, and it has a couple of properties worth exploiting.

No backtracking, ever

An anchored literal prefix compares a fixed number of characters at a known position and stops. There is no scanning and no backtracking, so performance is constant per line regardless of line length. On very large inputs the difference against an unanchored search is substantial.

startsWith beats regex

Most languages have a direct prefix comparison. It avoids the regex engine entirely and cannot be confused by metacharacters in the prefix โ€” a path containing . or + needs no escaping.

If the input is sorted, all lines sharing a prefix are contiguous. look exploits this directly, and the same idea underlies prefix indexes in databases: a LIKE 'abc%' query can use an index while LIKE '%abc%' cannot, for exactly this reason.

Try it: Keep Lines Starting With on SeoWolf's Notepad.