Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any time or space overhead to case classes over regular classes in Scala?

Tags:

scala

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".)

like image 725
phoenix Avatar asked Oct 04 '11 21:10

phoenix


1 Answers

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.

like image 95
Rex Kerr Avatar answered Oct 29 '22 18:10

Rex Kerr