Is there any overhead at all in using case classes in Scala versus regular classes? Does it use any extra memory, do more in construction, or do more in field access? Or is it literally just free equals/hashcode/tostring/apply/unapply/etc for classes at the bottom of the type hierarchy?
My use case is a class that deserves to be a case class (immutable and equal if all fields are equal), but I'm in a domain where performance is critical.
(Please don't answer along the lines of "stop worrying about premature optimization".)
If you compile a minimal example:
class Ordinary(val i: Int) { }
case class Case(i: Int) { }
you find that the bytecode for the ordinary class is smaller (~700 vs. ~3500); you also find with javap -c -private -v <Classname>
that the constructor has an extra method call to the Product trait initializer (which doesn't actually do anything, so should be optimized away by the JIT compiler).
So for repeated use of one class, it shouldn't make much difference. If you have many thousands of such classes, you might find increased bytecode problematic.
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