scala ranges versus lists performance on large collections

前端 未结 4 1978
醉梦人生
醉梦人生 2021-01-01 04:06

I ran a set of performance benchmarks for 10,000,000 elements, and I\'ve discovered that the results vary greatly with each implementation.

Can anybody explain why c

4条回答
  •  不知归路
    2021-01-01 04:47

    It's hard to read the Scala source on my iPad, but it looks like Range's constructor isn't actually producing a list, just remembering the start, increment and end. It uses these to produce its values on request, so that iterating over a range is a lot closer to a simple for loop than examining the elements of an array.

    As soon as you say range.toList you are forcing Scala to produce a linked list of the 'values' in the range (allocating memory for both the values and the links), and then you are iterating over that. Being a linked list the performance of this is going to be worse than your Java ArrayList example.

提交回复
热议问题