4 ms·
I've opted for a similar approach "behind the scenes" for my (wildly incomplete, though now close to compiling itself) Ruby compiler: While you can usually stat
by vidarh 9y ago
I've opted for a similar approach "behind the scenes" for my (wildly incomplete, though now close to compiling itself) Ruby compiler: While you can usually statically determine most likely instance variables for Ruby classes, and optimize that by creating the equivalent of slots, you also need to be able to dynamically create more, so I allocate "slots" in the instances for any variables that I can see, and fall back on the equivalent of __dict__ for anything that's dynamically added.
I've always found it quite curious that Python made this explicit rather than an implementation detail (I get that there are slight semantic differences here in Python too) because it seems like such a useful optimization. And a similar approach can be used for method lookup too.
I wonder (and I don't have any measurements on this myself) what the relative benefits are to explicitly picking one over the other vs. automating it are. The downside of doing it automatically is that some types of objects might very well be very "sparse" in that it's not a given that all instance variables are used for all objects (this is more applicable in for vtables, especially in languages with single-rooted object hierarchies).
My intuition is that the overhead of a map/dict/hash table to store them is likely to usually outweigh the cost of quite a lot of unused instance variables, and so that inferring instance variables is generally likely to be an improvement.
- pmontra 9y agoDo you have a link to your Ruby compiler? EDIT found it in your profile http://www.hokstad.com/compiler http://www.hokstad.com/compiler and submitted to HN. Great series of posts. About Python, it's a little older than Ruby (its design started in 1989) and Guido worked on the ABC language at the beginning of the 80s. IMHO that difference shows in many places, for example in having to explicitly pass self as argument in method definitions. Newer languages do without it and programmers don't get confused at all. All those double underscore methods and the general explicitness of the language smell of 80s and of C. Not necessarily a bad thing but reading some Python code is like getting on a time machine.
- vidarh 9y agoThanks. It's long overdue some updates as I've done quite a lot of work since (though still moving slowly) and it's pretty close to being able to fully compile itself now. What you say makes sense, and I understand that it takes a lot of effort to clean those type of things up without hurting backwards compatibility. This specific distinction though seems like one where it'd still be possible to get most of the benefit by changing the implementation of __dict__ to make it do something similar to __slot__ under the hood, but fall back to a dict for dynamic properties.