From f7ba69436acc15da88a94b6af55076d3c7c912ca Mon Sep 17 00:00:00 2001 From: Yuki Nishijima Date: Sat, 11 Apr 2015 15:16:10 -0700 Subject: Speed up Levenshtein by 50% and reduce 97% of memory usage MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Calculating ------------------------------------- each_char 924.000 i/100ms each_codepoint 1.381k i/100ms ------------------------------------------------- each_char 9.320k (¡Þ 5.1%) i/s - 47.124k each_codepoint 13.857k (¡Þ 3.6%) i/s - 70.431k Comparison: each_codepoint: 13857.4 i/s each_char: 9319.5 i/s - 1.49x slower The full report can be found here: https://gist.github.com/yuki24/a80988f35aceac76f1d5 --- railties/lib/rails/generators.rb | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'railties/lib/rails/generators.rb') diff --git a/railties/lib/rails/generators.rb b/railties/lib/rails/generators.rb index 341291f08b..a7da92168d 100644 --- a/railties/lib/rails/generators.rb +++ b/railties/lib/rails/generators.rb @@ -267,10 +267,13 @@ module Rails d = (0..m).to_a x = nil - str1.each_char.each_with_index do |char1,i| + # avoid duplicating an enumerable object in the loop + str2_codepoint_enumerable = str2.each_codepoint + + str1.each_codepoint.with_index do |char1, i| e = i+1 - str2.each_char.each_with_index do |char2,j| + str2_codepoint_enumerable.with_index do |char2, j| cost = (char1 == char2) ? 0 : 1 x = [ d[j+1] + 1, # insertion -- cgit v1.2.3