Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf: reduce string comparisons in Levenshtein distance calculation #266

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

ramsyana
Copy link

Optimize Levenshtein distance algorithm performance

  1. Reducing the total number of string comparisons by half
  2. Making string character access more efficient
  3. Moving some calculations to compile time

Key changes:

  • Changed string comparison loop to avoid duplicate checks
  • Added character caching for faster access
  • Used compile-time initialization for the first row

perf: optimize Levenshtein distance implementation

- Move first row initialization to compile time using inline while
- Cache characters to reduce array access
- Use @intFromBool for cost calculation
- Eliminate redundant string comparisons by starting j at i+1
- Use maxInt(usize) instead of -1 for min_distance
- Improve type safety by using usize consistently

Performance: Reduces number of comparisons from n*(n-1) to n*(n-1)/2
@PEZ
Copy link
Contributor

PEZ commented Dec 19, 2024

Hi! I don't think we are allowed to do 1 and 3.

The output of this version is

❯ ./zig/code `cat input.txt`                                   
times: 1953
min_distance: 7

Which is only half of the work the reference implementations do.

The benchmark tries to measure how fast a language does some work, and it's probably also cheating to do the work beforehand. (But @bddicken be the judge!)

Making string access more efficient should be perfectly fine, though. Do you know how much performance that unlocks?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants