Shopify's involvement with TruffleRuby began half a year ago, with the goal of furthering the success of the project and Ruby community. TruffleRuby is an alternative implementation of the Ruby language (where the reference implementation is CRuby, or MRI) developed by Oracle Labs. TruffleRuby has high potential in speed, as it is nine times faster than CRuby on optcarrot, a NES emulator benchmark developed by the Ruby Core Team. I’ll walk you through a simple feature I investigated and implemented. It showcases many important aspects of TruffleRuby and serves as a great introduction to the project! Introduction to Ruby Lazy Initialization Ruby developers tend to use the double pipe equals operator ||= for lazy initialization, likely somewhat like this: Syntactically, the meaning of the double pipe equals operator is that the value is assigned if the value of the variable is currently not set. The common use case of the operator isn’t so much “assign if” and more “assign once”. This idiomatic usage is a subset of the operator’s syntactical meaning so prioritizing that logic in the compiler can improve performance. For TruffleRuby, this would lead to less machine code being emitted as the logic flow is shortened. Analyzing Idiomatic Usage To confirm that this usage is common enough to be worth optimizing for, I ran static profiling on how many times this operator is used as lazy initialization. For a statement to count as a lazy initialization for these profiling purposes, we had it match one of the following requirements: The value being assigned is a constant (uses only literals of int, string, symbol, hash, array or is a constant variable). An example would be a ||= [2 * PI]. The statement with the ||= operator is in a function, an instance or class variable is being assigned, and the name of the instance variable contains the name of the function or vice versa. The function must accept no params. An example would be def get_a; @a ||= func_call. These criteria
NayaRead shows a summary and links to the original article. The full article is hosted on shopify.engineering.