A class per static field? Why or why not?
Maurizio Cimadamore
maurizio.cimadamore at oracle.com
Wed Dec 7 16:58:51 UTC 2022
On 07/12/2022 15:52, Dan Heidinga wrote:
> Why don't we put every static field in its own class?
There's a war story to be shared here:-) - you might want to take a
look at what the jextract tool does:
https://github.com/openjdk/jextract
To generate native bindings, jextract needs _a lot_ of constants,
downcall method handles, memory layouts, var handles, ...
The first iteration of jextract used static final fields, and startup
time was horrible given to the presence of so many field inits.
The current iteration of jextract uses a class holder for N constants
(with N configurable). This is a trade-off, to get good startup while
reducing the number of classes generated by the tool.
That said, the number of classes generated by jextract is _still_
astonishingly high (with big libraries you can easily get 200 of them).
While they are only loaded on-demand, users are often scared by this.
For this reason jextract also provides filtering capabilities: if you
only ever need to interact with 5 native functions, skip generation for
everything else.
This model has been serving us well so far, which confirms your "hunch".
Also, recent "tip" - since we can now have static fields inside methods,
we can also do this:
```java
X computeOnce() {
class Holder {
static final X x = ...
}
return Holder.x;
}
```
Which seems better than having N unrelated classes scattered around
(although you will see the classfiles for them if you run javac). We
have not tweaked jextract to do this (yet).
Of course, tools like jextract are a natural "killer application" for
lazy statics. Lazy statics would allow jextract to generate a lot less
code. And not only would the source code be more compact, but the size
of the generated classfiles would be much, much shorter too.
Cheers
Maurizio
More information about the leyden-dev
mailing list