[php-src] master: Optimize levenshtein a bit for memory usage (#13830)

From: Date: Tue, 02 Apr 2024 21:00:15 +0000
Subject: [php-src] master: Optimize levenshtein a bit for memory usage (#13830)
Groups: php.cvs 
Request: Send a blank email to php-cvs+get-127937@lists.php.net to get a copy of this message
Author: Niels Dossche (nielsdos) Committer: GitHub (web-flow) Pusher: nielsdos Date: 2024-04-02T23:00:10+02:00 Commit: https://github.com/php/php-src/commit/04e0d805540abdf6890079fbdc5ae74aace52c1b Raw diff: https://github.com/php/php-src/commit/04e0d805540abdf6890079fbdc5ae74aace52c1b.diff Optimize levenshtein a bit for memory usage (#13830) When all costs are equal, levenshtein fulfills the requirements of being a metric. A metric is symmetric, so we can swap the strings in that case. Since we use rows of a partial matrix of length |string2| we can make the choice of using string1 instead if |string1| < |string2|, which will optimize memory usage and CPU time. Changed paths: M ext/standard/levenshtein.c Diff: diff --git a/ext/standard/levenshtein.c b/ext/standard/levenshtein.c index b336be222086..fc71f8a7bccf 100644 --- a/ext/standard/levenshtein.c +++ b/ext/standard/levenshtein.c @@ -32,6 +32,15 @@ static zend_long reference_levdist(const zend_string *string1, const zend_string return ZSTR_LEN(string1) * cost_del; } + /* When all costs are equal, levenshtein fulfills the requirements of a metric, which means + * that the distance is symmetric. If string1 is shorter than string 2 we can save memory (and CPU time) + * by having shorter rows (p1 & p2). */ + if (ZSTR_LEN(string1) < ZSTR_LEN(string2) && cost_ins == cost_rep && cost_rep == cost_del) { + const zend_string *tmp = string1; + string1 = string2; + string2 = tmp; + } + p1 = safe_emalloc((ZSTR_LEN(string2) + 1), sizeof(zend_long), 0); p2 = safe_emalloc((ZSTR_LEN(string2) + 1), sizeof(zend_long), 0);

« previous php.cvs (#127937) next »