2

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

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Ahh thanks, this is what I meant. So it's only true for Set and Map.
Also, there is specialization to remove boxing, see more scala-notes.org/2011/04/specializing-for-primitive-types

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.