Thus, since Ruby garbage collects by stopping the program when memory is getting scarce, it is easy to see when garbage collection happens.
- I wrote two haikus in the same program -
The first shows how global constants are not garbage collected after being allocated. The second shows how local variables are garbage collected after the lifetime of their scope. This is important to realize when the programmer is dealing with enough memory that they could be close to running out of memory. Using this memory, the programmer can make sure not to make a variable a global constant unless it really needs to be.
- I rewrote the func example above in C explicitly handling the memory that Ruby does implicitly.
This creates an array for 10,000 strings, then in the function loops through and mallocs enough room for the string and adds it to the list. Then the function is called in the main loop, and since in Ruby the memory is not deallocated in the function, there is a loop after the function to deallocate all of the memory added to the list.