In the documentation about Scala value classes, it is mentioned that there are three cases when a value class needs to actually be allocated an instance:
Allocation Summary
A value class is actually instantiated when:
- a value class is treated as another type.
- a value class is assigned to an array.
- doing runtime type tests, such as pattern matching.
Is there a setting in the compiler or in the language features which would produce a warning when a value class needs to be instantiated?
No, not currently.
However, it is very rarely worth bothering with this kind of micro-optimisation.
If you have some very very hot code and you need to optimise it as far as possible then just try a few things and re-benchmark.
The JIT compiler will change what your code is doing at the machine level a lot of the time if the code is hot enough.
The overhead of allocating a value class is often not even measurable unless it is the only thing the thread is doing. See e.g. https://groups.google.com/forum/#!topic/scala-user/XdQnbcs2SRM for some benchmarks where value class allocation is not measurable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With