JFo JFo - 7 months ago 21
Java Question

Does Scala use special implementations for small collections?

I thought that a while ago I had read about Scala using "special" implementations when creating collections for a small amount of elements. E.g. for a

List
with only 4 elements, there is something like a "List4" that can carry exactly 4 elements, means that the implementation uses a fixed amount of fields (similar to the way tuples work, there are
Tuple1
,
Tuple2
,
Tuple3
...).

1.)
Unfortunately, I can't find this information anymore. Am I wrong about what I just claimed above (perhaps I mixed it up with another language)?

2.) The reason for my question: in Scala, I often catch myself using collections for the simplest things. E.g. when checking a small amount of variables for their values, I often do something like this:

def checkCoordinates(x: Int, y: Int, z: Int) = Seq(x, y, z).forall(_ >= 0)


In Java, I never would have done that. That's mainly because collections in Scala (and in functional languages in general) feel much more lightweight, at least regarding the syntax. But what about the performance standpoint and the habit of using collections for simple tasks (such as shown above)?

Answer

Sets are optimized you can see here:

https://github.com/scala/scala/blob/v2.11.7/src/library/scala/collection/immutable/Set.scala

There is Set1, Set2, Set3 and Set4

And same approach was taken for maps

https://github.com/scala/scala/blob/v2.11.7/src/library/scala/collection/immutable/Map.scala

For Seq and List it seems like a linked list (::) is created no matter what (not optimized).

Keep in mind you shouldn't really worry about this kind of things until profiling shows you that is causes performace issues for your application.

Comments