Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Garbage collection of class instance variables in ruby

If I use a method like

 def self.get_service_client
   return @service_client if !@service_client.nil?
   @service_client = #initialize logic
 end

Now @service_client is an instance variable of a class. How long is it in memory? Can I bank on it to not be re-initialized as long as the class is in memory (i.e like a static variable)?

like image 764
gnarsi Avatar asked Jul 11 '13 05:07

gnarsi


1 Answers

Classes are instances in Ruby, too, but when you define a class the usual way, it gets assigned to a constant, and that constant is referenced by other constants, preventing its collection. So, the class will be in memory indefinitely. Since the class will remain in memory, the class instance variable will too, as the class (which is an object instance) retains a reference to its instance variables.

As an aside, the idiomatic way to do this is:

def self.get_service_client
  @service_client ||= initialize_service_client
end
like image 107
Chris Heald Avatar answered Nov 11 '22 20:11

Chris Heald