Suppose I want to have a class like Java Date. Its only data member is a long which represents the milliseconds since 1970.
Would/Could it be of any performance benefit of just making a new Scala type:
type PrimitiveDate = Long
Then you can add methods by using implicit conversion, like it is done for int with RichInt. Does this “boxing” of the primitive type into a rich class involve any overhead (class creation)? Basically you could just have a static method
def addMonth(date: PrimitiveDate, months: Int): PrimitiveDate = date + 2592000000 * months
and let the type system figure out that it has to be applied when d addMonth 5
appears inside your code.
Edit
It seems that the alias you create by writing type PrimitiveDate = Long is not enforced by the scala compiler. Is creating a proper class, enclosing the Long, the only way to create an enforced type in Scala?
How useful do you consider being able to create an enforced type alias for primitive types?
Well, escape analysis should mean that the most recent JVMs do not actually have to create your rich wrapper in order to call the
addMonthmethod.The extent to which this actually occurs in practice will obviously depend on how much of a runtime hotspot the JVM decides that these methods are adding in object creation. When escape analysis is not happening, obviously the JVM will have to “box” (as you say) the
Longin a new instance of the wrapper class. It doesn’t involve “class creation” – it would involve “creating an instance of a class”. This instance, being short-lived would then be GC-d immediately, so the overhead (whilst small) is:These are obviously only going to be any kind of problem if you are definitely writing very low-latency code where you are trying to minimize garbage creation (in a tight loop). Only you know whether this is the case.
As for whether the approach will work for you (and escape analysis come to your aid), you’d have to test in the wild. Micro-benchmarks are notoriously difficult to write for this kind of thing.
The reason I don’t quite like these type aliases being part of a public API is that scala does not really enforce them as strictly as I would like. For example: