Stamping Out Overflow Checks in Ruby

submited by
Style Pass
2021-09-26 14:30:07

Someone on Reddit asked if it was possible to turn off overflow checking on integer arithmetic in Ruby. They said that they could guarantee that their arithmetic would not overflow, and therefore they’d like to not pay the cost for a pointless check.

As several people said in the thread, this isn’t possible in the standard implementation of Ruby, MRI, but it is possible and safe in TruffleRuby. And the great thing is it already happens automatically if you can prove using your code that your arithmetic will not overflow! Further than that, if your code doesn’t prove it already then it’s simple to add that proof using standard Ruby. To see if we can go a bit further, I’ve also tried adding a new zero-cost way to add proof that’s less safe but could be a tiny bit faster.

We can show that this does actually have a measurable impact on performance, so can be worth doing, especially since it can be done with plain Ruby code.

Leave a Comment