Review the newtype library for Scala with Owner of Estatico Studios LLC, Cary Robbins.
At LambdaConf 2018, Cary taught us how we can observe how we can cache instances so we can write efficient polymorphic functions. That's not all though, check it out here...
Zero Cost Abstractions Eliminating Runtime Overhead in Scala
Many of the standard abstractions employed today require some level of overhead, usually many new allocations to generate objects so we can perform special operations. We will tackle the following items, leveraging what we learn along the way for future optimizations.
- While AnyVal exists, it's not quite like Haskell's newtype. Is it possible to implement something like newtype for Scala?
- Polymorphic typeclass instances must be re-instantiated on every summon. GHC Haskell is smart enough to create these instances only once at compile time; is it possible to do the same in Scala?
- Generic programming via the Shapeless library requires many allocations of HList. Can we do generic programming in Scala without the need for extra runtime allocations?
We will review the design of the newtype library for Scala which demonstrates a pattern and general abstractions for creating and using newtypes. We'll also take a look at the Coercible type class as a general solution to efficiently converting between types. Next, we can observe how we can cache instances so we can write efficient polymorphic functions. This approach will be demonstrated simply with the definition of the Either monad. We can expand this principle further to build a @cached macro which takes care of this optimization for us. Finally, we will review the derivable project as an approach to building a zero-cost generic programming library. This leverages some of the tricks we've learned along the way, using safe coercions to encode metadata at the type level only, building extractors to access fields without the need to do any data copying whatsoever. Benchmarking our derivable project demonstrates a performance improvement over Shapeless by 20% and performs nearly identically to hand-written code.
This talk was given by Cary Robbins at LambdaConf 2018.