Hidden performance cost in Scala?

后端 未结 4 1624
傲寒
傲寒 2020-12-12 11:11

I came across this old question and did the following experiment with scala 2.10.3.

I rewrote the Scala version to use explicit tail recursion:

impor         


        
4条回答
  •  隐瞒了意图╮
    2020-12-12 12:10

    I changed the val

    private val t = 20
    

    to a constant definition

    private final val t = 20
    

    and got a significant performance boost, now it seems that both versions perform almost equally [on my system, see update and comments].

    I have not looked into into the bytecode, but if you use val t = 20 you can see using javap that there is a method (and that version is as slow as the one with the private val).

    So I assume that even a private val involves calling a method, and that's not directly comparable with a final in Java.

    Update

    On my system I got these results

    Java version : time: 14725

    Scala version: time: 13228

    Using OpenJDK 1.7 on a 32-Bit Linux.

    In my experience Oracle's JDK on a 64-Bit system does actually perform better, so this probably explains that other measurements yield even better results in favour of the Scala version.

    As for the Scala version performing better I assume that tail recursion optimization does have an effect here (see Phil's answer, if the Java version is rewritten to use a loop instead of recursion, it performs equally again).

提交回复
热议问题