Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Scala's cheapest type?

Tags:

types

scala

I need to use a type (any type) as a marker in an implicit as a type parameter, to distinguish it from another implicit. It's weird, but this may be another question.

Since I can use any type, I was thinking of using the cheapest one, in terms of memory footprint and initialization time. It may not affect performance too much in this case, but the question is interesting: Which one is Scala's cheapest type?

In Java, the answer is obviously java.lang.Object. But Scala has a few "interesting" types: Any, AnyVal types, and bottom types with possible optimizations around them. The Nothing type cannot be instantiated, so it is excluded from this comparison.

like image 711
Adrian Avatar asked Feb 05 '11 08:02

Adrian


2 Answers

It depends on your exact problem, but the cheapest construct in Scala - or in any language - has got to be one that doesn't exist at all... (at least, not at runtime)

Allow me to introduce Phantom Types, allowing the compiler to statically do the Right Thing, but erased to nothingness before they hit the JVM.

In a similar vein, you can easily distinguish two differently typed objects without needing any marker fields. This is a good candidate for case objects, and works really nicely alongside pattern matching.

like image 93
Kevin Wright Avatar answered Sep 20 '22 04:09

Kevin Wright


I'm not sure I get what you mean with "cheapest type"... In Java cheapest numerical type in terms of memory can be byte, but from performance POV Java is optimized to work with int. In fact many (or most) languages are optimized to work with int (even DB engines). Scala is JVM language, so I would say that better to use int.

UPDATE: if the question is about "marked / not marked" suitable data type, I would use boolean primitive.

if you type boolean in a Scala program, the type you'll actually get is scala.Boolean. Or if you type float, you'll get scala.Float. When you compile your Scala code to Java bytecodes, however, Scala will compile these types to Java's primitive types where possible to get the performance benefits of Java's primitive types.

Nothing is an Any, which is kind of Object in Java, and any Object needs more memory than any primitive type

And btw, using boolean as marker is natural, it improves your code readability (and hence support, understanding by others). Even if there is anything else, more optimized I would not do premature optimization and would choose boolean.

like image 43
Maxym Avatar answered Sep 20 '22 04:09

Maxym