Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Various ways of creating Objects in Ruby

Are these methods of creating an empty Ruby Hash different? If so how?

myHash = Hash.new

myHash = {}

I'd just like a solid understanding of memory management in Ruby.

like image 868
SundayMonday Avatar asked Feb 11 '26 08:02

SundayMonday


2 Answers

There are many ways you can create a Hash object in Ruby, though the end result is the same sort of object:

hash = { }
hash = Hash.new
hash = Hash[]
hash = some_object.to_h
hash = YAML.load("--- {}\n\n")

As far as memory considerations go, an empty Hash is significantly smaller than one with even a singular value in it. Arrays tend to be smaller than Hashes at small sizes, but will be more efficient at larger scales.

In practice, though, the important thing to remember in Ruby is that every time you create an object it costs you something, even if it's only an infinitesimal amount. These little hits add up if you're needlessly creating billions of objects.

Generally you should avoid creating structures that will not be used, and instead create them on demand if that wouldn't complicate things needlessly. For example, a typical pattern is:

def cache
  @cache ||= { }
end

Until this method is called, the cache Hash is never defined. The memory savings in this instance is nearly insignificant, but if that was loading a large configuration file or importing several hundred MB of data from a database you can imagine the savings would be significant in those instances where that data is not exercised.

like image 168
tadman Avatar answered Feb 15 '26 12:02

tadman


The two methods are exactly equivalent.

like image 25
Marnen Laibow-Koser Avatar answered Feb 15 '26 10:02

Marnen Laibow-Koser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!