I’ve tried different collections in Scala to sum it’s elements and they are much slower than Java sums it’s arrays (with for cycle). Is there a way for Scala to be as fast as Java arrays?
I’ve heard that in scala 2.8 arrays will be same as in java, but they are much slower in practice
Indexing into arrays in a while loop is as fast in Scala as in Java. (Scala’s “for” loop is not the low-level construct that Java’s is, so that won’t work the way you want.)
Thus if in Java you see
in Scala you should write
and if you do your benchmarks appropriately, you’ll find no difference in speed.
If you have iterators anyway, then Scala is as fast as Java in most things. For example, if you have an ArrayList of doubles and in Java you add them using
then in Scala you’ll be approximately as fast–if using an equivalent data structure like ArrayBuffer–with
and not too far off the mark with either of
Keep in mind, though, that there’s a penalty to mixing high-level and low-level constructs. For example, if you decide to start with an array but then use “foreach” on it instead of indexing into it, Scala has to wrap it in a collection (
ArrayOpsin 2.8) to get it to work, and often will have to box the primitives as well.Anyway, for benchmark testing, these two functions are your friends:
For example: