lotus/utils — pull request #34 by KillaPL (2014-10-19 13:18:45+00:00)
Title: String underscore optimisation

I changed how String#underscore is implemented to avoid unnecessary object allocations.
Benchmarks between old and suggested versions:

Calculating -------------------------------------
slow 9607 i/100ms
fast 10075 i/100ms
-------------------------------------------------
slow 106749.4 (±0.2%) i/s - 537992 in 5.039784s
fast 112150.6 (±0.4%) i/s - 564200 in 5.030835s

To calculate object allocations I called underscore 1000 times on.

string = Lotus::Utils::String.new 'LotusUtils'
other = Lotus::Utils::String.new 'APIDoc'

I benchmarked 2 strings to make sure all gsubs are called in the benchmark.
Results:

Allocations for slow:
sourcefile sourceline class count
------------------------------- ---------- -------------------- -----
/lib/lotus/utils/string.rb 74 String 7000
/lib/lotus/utils/string.rb 74 MatchData 2000
/lib/lotus/utils/string.rb 73 String 7000
/lib/lotus/utils/string.rb 198 String 4000
/lib/lotus/utils/string.rb 72 String 2000
/lib/lotus/utils/string.rb 72 Lotus::Utils::String 2000
/lib/lotus/utils/string.rb 75 String 2000
/lib/lotus/utils/string.rb 73 MatchData 2000

Allocations for fast:
sourcefile sourceline class count
------------------------------- ---------- -------------------- -----
/lib/lotus/utils/string.rb 198 String 4003
benchmarks/string_underscore.rb 34 Lotus::Utils::String 2000
benchmarks/string_underscore.rb 31 String 4000
benchmarks/string_underscore.rb 31 MatchData 2000
benchmarks/string_underscore.rb 32 String 4000
benchmarks/string_underscore.rb 32 MatchData 2000
/lib/lotus/utils/string.rb 198 Regexp 1

Which adds up to ~5% better performance and over 35% less object allocations in worst case.