Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Integer and Fixnum?

Tags:

ruby

I know that the Fixnum class inherits from the Integer class. But what is the actual difference between them? Are there any use cases where we sometimes use Fixnum, and sometimes use Integer instead?

like image 640
TheOneTeam Avatar asked Jan 27 '14 03:01

TheOneTeam


People also ask

What is a Fixnum?

A Fixnum holds Integer values that can be represented in a native machine word (minus 1 bit). If any operation on a Fixnum exceeds this range, the value is automatically converted to a Bignum . Fixnum objects have immediate value.

What is Bignum in Ruby?

Bignum objects hold integers outside the range of Fixnum. Bignum objects are created automatically when integer calculations would otherwise overflow a Fixnum. When a calculation involving Bignum objects returns a result that will fit in a Fixnum, the result is automatically converted.


2 Answers

UPDATE: As of Ruby 2.4, the Fixnum and Bignum classes are gone, there is only Integer. The exact same optimizations still exist, but they are treated as "proper" compiler optimizations, i.e. behind the scenes, invisible to the programmer.


This is somewhat confusing. Integer is the real class that you should think about. Fixnum is basically a performance optimization that should never have been made visible to the programmer in the first place. (Compare this with flonums in YARV, which are implemented entirely as an optimization inside the VM, and never exposed to the programmer.)

Basically, Fixnums are fast and Bignums are slow(er), and the implementation automatically switches back and forth between them. You never ask for one of those directly, you will just get one or the other, depending on whether your integer fits into the restricted size of a Fixnum or not.

like image 85
Jörg W Mittag Avatar answered Oct 16 '22 15:10

Jörg W Mittag


You never "use" Integer. It is an abstract class whose job is to endow its children (Fixnum and Bignum) with methods. Under effectively no circumstances will you ever ask for an object's class and be told that it is an Integer.

like image 43
matt Avatar answered Oct 16 '22 16:10

matt