Skip to content

Commit

Permalink
[Optimized]: Removed several bounds checks
Browse files Browse the repository at this point in the history
- For the init loop,  The compiler is unable to prove that
"<= lenS1" is essentially same as "< len(x)". So we mention it
explicitly.

- Made a dummy bounds check to prevent further checks for x[lenS1]
down below. And this also takes care of x[j-1] since j is <= lenS1.

This effectively reduces the number of bounds checks from 7 to just 1,
which is the dummy call to x[lenS1]. The compiler, as of 1.12,
is unable to determine that lenS1 is indeed a positive number. So
lenS1+1 will be positive, and hence x[lenS1] should be within bounds
of x. As a result, this is unavoidable.

name              old time/op  new time/op  delta
Simple/ASCII-4     473ns ± 2%   365ns ± 1%  -22.85%  (p=0.000 n=10+10)
Simple/French-4    897ns ± 2%   680ns ± 2%  -24.23%  (p=0.000 n=10+10)
Simple/Nordic-4   1.83µs ± 1%  1.33µs ± 2%  -27.23%  (p=0.000 n=8+9)
Simple/Tibetan-4  1.40µs ± 2%  1.15µs ± 2%  -17.56%  (p=0.000 n=10+10)
  • Loading branch information
agnivade committed Mar 31, 2019
1 parent 58e879e commit 1e1f2ae
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 5 deletions.
8 changes: 4 additions & 4 deletions README.md
Expand Up @@ -38,10 +38,10 @@ Benchmarks

```
name time/op
Simple/ASCII-4 449ns ± 1%
Simple/French-4 872ns ± 1%
Simple/Nordic-4 1.74µs ± 1%
Simple/Tibetan-4 1.34µs ± 1%
Simple/ASCII-4 365ns ± 1%
Simple/French-4 680ns ± 2%
Simple/Nordic-4 1.33µs ± 2%
Simple/Tibetan-4 1.15µs ± 2%
name alloc/op
Simple/ASCII-4 96.0B ± 0%
Expand Down
2 changes: 2 additions & 0 deletions go.mod
@@ -1 +1,3 @@
module github.com/agnivade/levenshtein

go 1.13

This comment has been minimized.

Copy link
@EwanValentine

EwanValentine Apr 17, 2019

Does this version exist yet? Getting build errors related to this as it's an indirect dependency

This comment has been minimized.

Copy link
@agnivade

agnivade Apr 17, 2019

Author Owner

What version are you using ? If you are using module-mode, then it will not work below 1.11.4.

5 changes: 4 additions & 1 deletion levenshtein.go
Expand Up @@ -43,10 +43,13 @@ func ComputeDistance(a, b string) int {

// init the row
x := make([]int, lenS1+1)
for i := 0; i <= lenS1; i++ {
for i := 0; i < len(x); i++ {
x[i] = i
}

// make a dummy bounds check to prevent the 2 bounds check down below.
// The one inside the loop is particularly costly.
_ = x[lenS1]
// fill in the rest
for i := 1; i <= lenS2; i++ {
prev := i
Expand Down

0 comments on commit 1e1f2ae

Please sign in to comment.