11

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:

  1. a value class is treated as another type.
  2. a value class is assigned to an array.
  3. 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?

Prikso NAI
  • 2,592
  • 4
  • 16
  • 29

1 Answers1

1

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.

Rich
  • 15,048
  • 2
  • 66
  • 119