title: Can I save Ruby memory by explicitly destroying instance variables?
body: <p>My rails app's memory usage increases steadily when no one uses the app, and faster when someone is. Left alone, it exceeds the Heroku limit of 512 mb in a few hours.</p>
  
  <hr>
  
  <p><strong>Edit #1:</strong> After a few changes detailed below, I observe that memory usage levels off below the max. I don't think there is a memory leak; it looks logarithmic. I will apply some stress (usage) to see how it holds up.</p>
  
  <hr>
  
  <p>I have certain methods that create Hash, String, and (numeric) Array instance variables. Could I reduce memory usage by clearing these instance variables from memory after they are no longer needed?</p>
  
  <p>I was thinking of setting the variable equal to nil after I'm done with it, or using <a href="http://apidock.com/ruby/Object/remove_instance_variable" rel="nofollow">remove_instance_variable</a>, as in <code>remove_instance_variable(:@foobar)</code> every time I'm totally done with a variable.</p>
  
  <p>Is this a sensible thing to try? If so, is this a good way of removing instance variables? Or must I run <code>GC.start</code>?</p>
  
  <hr>
  
  <p><strong>Edit #2:</strong> The only reason I am using instance variables is to pass them between multiple smaller methods, all within one Service Object. So perhaps it would use less memory to simply have one larger (less legible) method that only uses local variables? Or params taken by each smaller method? Basically, I am looking for the most memory-efficient way to run a large method that involves many variables.</p>
  
  <hr>
  
  <hr>
  
  <p><strong>Edit #3:</strong> After running the large method a few times in production, memory usage jumps up (from ~60% to ~80% of the max 512MB) and then stays flat. So I'm fairly sure that in addition to other ways of optimizing memory usage by the app, this particular method is a culprit.</p>
  
  <hr>
  
  <p>I have tried several other approaches to reducing my memory usage, including:</p>
  
  <ul>
  <li>Deleting unneeded gems</li>
  <li>Changing "foo" + "bar" to "foo" &lt;&lt; "bar"</li>
  <li>Reduced excessive ActiveRecord queries</li>
  </ul>
  
  <p>In my heroku console:</p>
  
  <pre><code>irb(main):001:0&gt; ObjectSpace.count_objects
  =&gt; {:TOTAL=&gt;557200, :FREE=&gt;116793, :T_OBJECT=&gt;18594, :T_CLASS=&gt;7161, :T_MODULE=&gt;1016, :T_FLOAT=&gt;9, :T_STRING=&gt;261936, :T_REGEXP=&gt;2270, :T_ARRAY=&gt;68972, :T_HASH=&gt;11010, :T_STRUCT=&gt;841, :T_BIGNUM=&gt;10, :T_FILE=&gt;6, :T_DATA=&gt;39779, :T_MATCH=&gt;91, :T_COMPLEX=&gt;1, :T_RATIONAL=&gt;901, :T_SYMBOL=&gt;781, :T_NODE=&gt;24726, :T_ICLASS=&gt;2303}
  </code></pre>