require 'benchmark/ips' Benchmark.ips do |x| x.report('Fixnum') endĪnd the results. We can check this with the following simple benchmark. Operating with Bignum (behind the scene, such Integer numbers are still Bignum ) is slower. There are two main reasons: performance and memory consumption. It stores the number in its reference pointer, which takes 8 bytes only. That means Ruby VM doesn’t allocate extra memory for every number (from -2⁶² to 2⁶²-1). After slightly decreasing the power number, we can end up with the new number. That means my initial gut feeling didn’t bring me anywhere. What would be the size of 2⁶³-1 in Ruby’s object space? Let’s find out. You can read more about the memory internals of Ruby here. Now, the size is 40 bytes, equal to the RValue struct size that Ruby allocates to store objects. To get the actual size of the object, we should use msize_of instead. Having this in mind, Integer#size doesn’t return the full size of the object but only its number part. For example, Symbols and Fixnums (now with the Bignum part of the Integer class) are special. Some objects may have different behavior than others due to internal implementation. As we know, everything in Ruby is an object: including numbers. (-1*(2**64-1)).size => 8 How can Ruby fit 8 bytes of data and a sign into 8 bytes?įirst of all, the size method depends on the machine.īut that’s not all. But checking how many bytes would take a negative number killed that idea. (2**64).size => 9įor a second, I thought: okay, maybe it’s stored like an unsigned 8 bytes integer (all 8 bytes for the number itself). We will come back to this later.įor a reason I don’t remember, I decided to find when Ruby would start returning 9 bytes, and, surprisingly, for me, it wasn’t 2⁶³. My first attempt was 2⁶³-1 as a signed 8 bytes integer (1 bit for a sign and 63 bit for the number itself).
0 Comments
Leave a Reply. |