Skip to content
Alessandro Autiero
Go back

OptionalDesugarer: Type safety with no overhead

Introduction

Hello, I’m back with another compiler related project. If you don’t remember me/didn’t read my previous post about Reified, an annotation processor that adds support for ratification in Java 11 and upwards, you can check it out here. The same warnings about the use of non supported compiler APIs apply for this project as well, if you want to know more check the linked thread.

Abstract

Optional is a wrapper class introduced in Java 8 to help developers avoid the all-mighty null pointer exception. This class, though, isn’t intended to be used as Haskell’s Maybe or Ocaml’s Some: it is by design a limited mechanism intended to be only used as a return value. As usual, some didn’t bother reading the documentation so it can be seen as a method’s parameter or class’ field in some fairly large projects(looking at you Selenium). This, though, isn’t the point of the thread so let’s digress.

The Idea

A month ago, I read a thread reposted on this subreddit from Rust’s where the performance of Java’s Optional and Rust’s Option was put to the test. You can find the article here. In short, Java’s offering didn’t quite keep up to be fairly polite. This got me thinking and I decided that I wanted to fix this issue. So I came up with the idea of using AST manipulation to desugar Optional calls in null safe calls. This is the same approach used by Java’s compiler for lambdas, but it took some time to discover it considering that close to nobody(literally) has bothered using the internal javac API or let alone wrote some interesting articles about it.

The Implementation

In the beginning, I thought about using an annotation processor, but quickly I realized that a compiler plugin would be more suitable. Considering that I had no idea that Javac has a mechanism built in to implement desugaring, I tried to contextualize all Optional calls based on the enclosing trees. Once I understood that such an approach would never work, I started to look for alternatives. Turns out that looking through Javac’s source code for the word desugar using IntelliJ’s “find all shortcut” was all the input I needed to find the TreeTranslator class. Once I had a better base for my project, I really started to think about how to implement it properly. The problem with Optional calls is that most contain lambdas. Desugaring a method call is easy, a lambda not so much. I found a class in Javac’s source called LambdaToMethod, but it doesn’t really do what I would have hoped so I actually implemented the whole process by myself. The thing that took me ages to figure out is how to correctly pass local scoped variables to the lambdas in order to not make the compilation process fail. This work can be found inside the FunctionalTransformer class. I then implemented a class-based transformer system for every instruction supported up to Java 17 by Optional, fixed some bugs and published a release. I missed some steps in the story, but it’s simply too much to explain here. If anyone reads the source code and has any questions/finds a bug, I’m more than happy to elaborate on the implementation

Some Benchmarks

As seen in the git repository, I run some benchmarks inspired by the article’s author. You can check out the source code and the logs for every benchmark in the benchmark folder of the project’s repository. Here is an extract:

Code from the article without the plugin (WORST)
The code used by the author of the original article without using this plugin

Benchmark                    Mode  Cnt     Score     Error  Units OptionBenchmark.sumNulls     avgt    5   719,811 ±   2,310  us/op OptionBenchmark.sumOptional  avgt    5  3109,123 ±  39,577  us/op OptionBenchmark.sumSimple    avgt    5   342,732 ±  12,183  us/op

Code from the article with the plugin
The code used by the author of the original article using this plugin

Benchmark                    Mode  Cnt    Score    Error  Units
OptionBenchmark.sumNulls     avgt    5  707,844 ±  6,488  us/op
OptionBenchmark.sumOptional  avgt    5  746,546 ±  6,932  us/op
OptionBenchmark.sumSimple    avgt    5  340,930 ± 11,849  us/op

Code from the article with optimized getOptionalNumber and plugin (BEST)
The code used by the author with a refactor of the getOptionalNumber method to improve efficiency and the plugin

Benchmark                    Mode  Cnt    Score    Error  Units
OptionBenchmark.sumNulls     avgt    5  719,530 ±  3,612  us/op
OptionBenchmark.sumOptional  avgt    5  338,803 ±  2,524  us/op
OptionBenchmark.sumSimple    avgt    5  339,972 ± 11,211  us/op

Code from the article with optimized sumOptional, for loop replaced with LongStream, and plugin
The code used by the author with a refactor of the getOptionalNumber method to improve efficiency, a LongStream implementation of the sumOptional method, and the plugin

Benchmark                    Mode  Cnt    Score    Error  Units
OptionBenchmark.sumNulls     avgt    5  772,831 ±  9,565  us/op
OptionBenchmark.sumOptional  avgt    5  373,321 ±  8,012  us/op
OptionBenchmark.sumSimple    avgt    5  340,566 ± 13,119  us/op

So I guess that we made it, Optional is as fast as the sumSimple benchmark in the best scenario. I wanted to run the tests using Graal’s native image to try and beat Rust, but they somehow got worse results, even without the plugin. I’d be happy to know why in the comments.

Repository and Installation Instructions

Here is a link to the repo: Auties00/OptionalDesugarer. You can easily try out the project by following the instructions in the repo. If you find any bug, please open an issue.


Originally posted on r/java on November 19, 2021.



Previous Post
Reified - Enhanced Type Parameters in Java 11 and upwards
Next Post
Named and Optional Parameters in Java