Closed bitwise-aiden closed 8 months ago
Nice! The way I read this code is it trims any .000 at the end. And it's faster to do that if we check for match? before hand.
Correct!
This is good! Is .sub faster? Probably not. I've not measured it, but I suspect that we need
gsub
to remove all training0
.
When instantiating a large volume of
Measurable
objectsgsub
is run indiscriminately. I'm adding a defensive check as benchmarks show this is a lot faster.bench.rb
```ruby require "benchmark/ips" class BenchGsub VALUES = 1000.times.map { |v| (v / 10).to_s } class << self def raw VALUES.each { |v| v.gsub(/\.0*\Z/, "") } end def check(value) VALUES.each { |v| v.gsub(/\.0*\Z/, "") if /\.0*\Z/.match?(v) } end end end Benchmark.ips do |x| x.report("raw", &BenchGsub.method(:raw)) x.report("check", &BenchGsub.method(:check)) x.compare! end ```