scala ranges versus lists performance on large collections

前端 未结 4 1948
醉梦人生
醉梦人生 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:43

    This is an educated guess ...

    I think it is because in the fast version the Scala compiler is able to translate the key statement into something like this (in Java):

    List millions = new ArrayList();
    for (int i = 0; i <= 10000000; i++) {
        if (i % 1000000 == 0) {
            millions.add(i);
        }
    }
    

    As you can see, (0 to 10000000) doesn't generate an intermediate list of 10,000,000 Integer objects.

    By contrast, in the slow version the Scala compiler is not able to do that optimization, and is generating that list.

    (The intermediate data structure could possibly be an int[], but the observed JVM size suggests that it is not.)

提交回复
热议问题