-
Notifications
You must be signed in to change notification settings - Fork 113
Description
Hi there,
I'm experiencing some pretty interesting behavior when summing units together. I'm on Ruby 2.5.0 and Rails 5.1.5 but this can be reproduced in just an IRB console in Ruby 2.5.0
require "ruby-units"
require 'bigdecimal'
require 'bigdecimal/util'
a = [
[2.025, "gal"],
[5.575, "gal"],
[8.975, "gal"],
[1.5, "gal"],
[9, "gal"],
[1.85, "gal"],
[2.25, "gal"],
[1.05, "gal"],
[4.725, "gal"],
[3.55, "gal"],
[4.725, "gal"],
[3.75, "gal"],
[6.275, "gal"],
[0.525, "gal"],
[3.475, "gal"],
[0.85, "gal"]
].map{|ns,nu| Unit.new(ns.to_d, nu)}
a.sumThis runs really slow. Like really slow.
Instead of just doing the last linea.sum let's do a[0..10].sum. It runs pretty quickly.
Now do this. (same scalar and unit values as before with no .to_d coercion.)
b = [
[2.025, "gal"],
[5.575, "gal"],
[8.975, "gal"],
[1.5, "gal"],
[9, "gal"],
[1.85, "gal"],
[2.25, "gal"],
[1.05, "gal"],
[4.725, "gal"],
[3.55, "gal"],
[4.725, "gal"],
[3.75, "gal"],
[6.275, "gal"],
[0.525, "gal"],
[3.475, "gal"],
[0.85, "gal"]
].map{|ns,nu| Unit.new(ns, nu)}
b.sumIt runs very quickly. The numbers are floats, not BigDecimal.
What I've found is that summing arrays of units where the scalar value is a BigDecimal and the .count is greater than let's say 12 it performs abysmally. However summing arrays of units with a .count of less than 10 it works just fine.
The reason I'm dealing with BigDecimal is because that's what I get back from Rails on a decimal column.
Let me know if you need more detail.