Stack performance in programming languages

前端 未结 8 2182
孤城傲影
孤城傲影 2020-12-31 17:41

Just for fun, I tried to compare the stack performance of a couple of programming languages calculating the Fibonacci series using the naive recursive algorithm. The code is

8条回答
  •  轮回少年
    2020-12-31 18:13

    One possibility is that the C compiler is optimizing on the guess that the first branch (n < 2) is the one more frequently taken. It has to do that purely at compile time: make a guess and stick with it.

    Hotspot gets to run the code, see what actually happens more often, and reoptimize based on that data.

    You may be able to see a difference by inverting the logic of the if:

    public static int fib(int n) {
     if (n >= 2) return fib(n-1) + fib(n-2);
     return 1;
    }
    

    It's worth a try, anyway :)

    As always, check the optimization settings for all platforms, too. Obviously the compiler settings for C - and on Java, try using the client version of Hotspot vs the server version. (Note that you need to run for longer than a second or so to really get the full benefit of Hotspot... it might be interesting to put the outer call in a loop to get runs of a minute or so.)

提交回复
热议问题