Posts tagged performance

Important Ruby Memory Management Concepts

2019-07-22

How does Garbage Collection work in Ruby? At its most basic, when you create a Ruby object, memory is allocated for it. The object lives for a while, hopefully doing some useful work. Then, when the object is no longer in use, Ruby marks that section of the memory as available for future use by other objects. 2 different sets of memory Malloc heap: Everything in your program is included in this section of memory. It’s not released back to the operating system unless the memory is known to be unused by Ruby at the end of a garbage collection. Examples - string buffers and data structures managed by C extension. Ruby object heap: Subset of malloc heap. Most ruby objects live here. Large ones point to malloc heap. Point of main focus. Mark and Sweep You can call the strategy as . But what is it? Mark First, allocating memory takes some time, so Ruby pre-allocates thousands of objects to have them ready when you need them. This is called the “free list.” Ruby uses a tricolor mark and sweep garbage collection algorithm. Every object is marked either white, black, or gray, hence the name tricolor. Starts with mark phase and marks everything as white. White means not yet reviewed. Marks grey for all objects that are accessible. These may be constants or variables in the current scope.This means that the object should not be garbage collected, but hasn’t been fully examined. For each object marked with a gray flag, all its connections are examined. For each reviewed object, if it has a white flag, the flag is changed to gray. Finally, after all the connections of a given object have been examined, the initial root object with the gray flag is marked with a black flag. A black flag means “do not garbage collect, this object is in use”. The collector then starts examining another object with a gray flag. After all the objects with gray flags have been examined, all objects in the Ruby heap should have either a black flag or a white flag. Black flagged objects should not be garbage collected. White flagged objects are not connected to any black-flagged objects and can be deleted. Sweep The memory that the white flagged objects are allocated in is then returned to the Ruby heap. This is the ‘sweep’ phase. Basically, calls with the object_id for each white objects. As you can see, most of the complexity is in phase. Generational Garbage Collection Introduced in Ruby 2.1. Based on the theory that most objects are used briefly and then aren’t needed anymore Ruby…

Simple lazy loader

2019-07-15

Simple lazy loader to lazy load images, videos, iframes and background images. This is without any dependencies. Doesn’t work on browsers not supporting intersection observer API. However, you can polyfill it with or