JFo JFo - 6 months ago 9x
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

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

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)?


Sets are optimized you can see here:


There is Set1, Set2, Set3 and Set4

And same approach was taken for maps


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.