HeadlinesBriefing HeadlinesBriefing.com

Object Maps, Shapes and Hidden Classes Explained

Hacker News •
×

In many dynamically typed languages such as Python, Ruby and JavaScript, objects look like mappings of attribute names to values. This flexibility encourages runtime implementers to model attributes with a hash table, which seems a natural fit since hash tables are good at mapping names to values.

However, a hash table approach has drawbacks. Hashing and probing are slow for a very common operation. The hash table also adds an indirection, forcing a jump from the object to a separate storage structure. As a result, a simple attribute access like a.b can take hundreds or thousands of CPU instructions, including multiple dependent memory loads. Attributes are accessed frequently, so storing them inline on the object would be far more efficient.

To address this, runtimes use structures known variously as maps, layouts, shapes, or hidden classes. These optimize the reading, writing and storage of attributes. Many production runtimes contain complex, domain-specific edge cases, and many blog posts offer high-level overviews without implementation detail.

The author builds on CF Bolz-Tereick's A Simple Object Model, which models Python with reasonable fidelity. Rather than covering the class and method machinery, the author focuses on the instance attribute and map parts, extracting a reduced, clean map system in under 500 lines of code that a reader can hold in their head at once.

Source: Hacker News · Summarized by HeadlinesBriefing