Project

General

Profile

Actions

Bug #21851

closed

Performance difference between / operator and fdiv

Bug #21851: Performance difference between / operator and fdiv

Added by mbrown1intel (Michael Brown) 28 days ago. Updated 13 days ago.

Status:
Closed
Assignee:
-
Target version:
-
ruby -v:
ruby 4.0.1 (2026-01-13 revision e04267a14b) +PRISM [x64-mingw-ucrt]
[ruby-core:124631]

Description

Benchmarking fdiv against the / operator, it seems like fdiv is significantly slower. As far as I'm aware there's no functional difference between these two methods.

I first ran this on 2.6, and then checked against 4.0 to make sure it hadn't been fixed in the meantime, and saw the same results.

require 'benchmark'

n = 500_000_000
c = nil

Benchmark.bm do |benchmark|
  benchmark.report("to_f ") do
    n.times do |i|
      c = n / i.to_f
    end
  end

  benchmark.report("fdiv ") do
    n.times do |i|
      c = n.fdiv(i)
    end
  end
end
           user     system      total        real
to_f  37.672000   0.110000  37.782000 ( 38.714876)
fdiv 113.016000   0.265000 113.281000 (116.428442)

Related issues 1 (0 open1 closed)

Related to Ruby - Bug #13078: with Integer a and b, a.fdiv(b) sometimes inaccurate than Rational(a, b).to_fClosedActions

Updated by byroot (Jean Boussier) 27 days ago Actions #1 [ruby-core:124632]

Profile with / .to_f: https://share.firefox.dev/4rbNEEW

Profile with fdiv: https://share.firefox.dev/4qeMwzK

In short, fdiv end up in the gcd path, which is indeed much slower.

We could certainly recognize this case and add a fastpath, not sure I'd consider this a bug though.

Updated by mame (Yusuke Endoh) 27 days ago Actions #2

  • Related to Bug #13078: with Integer a and b, a.fdiv(b) sometimes inaccurate than Rational(a, b).to_f added

Updated by mame (Yusuke Endoh) 27 days ago Actions #3 [ruby-core:124633]

It seems Integer#fdiv uses gcd for accuracy in #13078. I'm not entirely sure why they only aimed to make fdiv accurate but not /.

Anyway, is this difference causing any real-world issues? If so, it's worth considering a fix. If just for performance consistency, doing nothing might be good enough.

Updated by mbrown1intel (Michael Brown) 26 days ago Actions #4 [ruby-core:124642]

No, this isn't causing me any issues, I just would prefer fdiv for my own codebase for readability. But with that large of a performance difference I think I would stick with "/".

Updated by nobu (Nobuyoshi Nakada) 13 days ago Actions #6

  • Status changed from Open to Closed

Applied in changeset git|74a4e2e66d14fed7d6ade09345a54ed14bc106cc.


[Bug #21851] Divide as double if accurate

Actions

Also available in: PDF Atom