Skip to content

Commit

Permalink
remove some possible branches
Browse files Browse the repository at this point in the history
  • Loading branch information
anderj017 committed Sep 26, 2020
1 parent 73bdea8 commit 03f9200
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 12 deletions.
23 changes: 13 additions & 10 deletions src/levenshtein_distance.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use std::cmp::max;
use std::num::Wrapping;

pub struct LevenshteinDistanceCalc {
Expand All @@ -15,8 +14,8 @@ impl LevenshteinDistanceCalc {
fn build_cache(&mut self, target_len: usize) {
// if we know the max length we can pre-allocate and don't need this
// save a branch that'll never be called
let alloc_size = max(self.cache.len(), target_len);
self.cache.reserve(alloc_size);
//let alloc_size = max(self.cache.len(), target_len);
//self.cache.reserve(alloc_size);

self.cache.clear();
for i in 0..=target_len {
Expand All @@ -25,13 +24,17 @@ impl LevenshteinDistanceCalc {
}

pub fn calc(&mut self, source: &str, target: &str) -> usize {
if source.is_empty() {
return target.len();
}

if target.is_empty() {
return source.len();
}
//assert!(!source.is_empty());
// if we can assume neither is empty, we don't need these branches
// if source.is_empty() {
// return target.len();
// }

// this was already not possible (redundant branch)
//assert!(!target.is_empty());
//if target.is_empty() {
// return source.len();
//}

let target_len = target.len();

Expand Down
4 changes: 2 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ fn main() {

{
for _ in 0..10000 {
let mut last_value = "";
for line in &lines {
let mut last_value = unsafe { lines.get_unchecked(0) };
for line in lines.iter().skip(1) {
leven_dist_calc.calc(last_value, line);
last_value = line;
}
Expand Down

0 comments on commit 03f9200

Please sign in to comment.