How can the compile-time be (exponentially) faster than run-time?

前端 未结 3 2062
面向向阳花
面向向阳花 2020-12-28 12:21

The below code calculates Fibonacci numbers by an exponentially slow algorithm:

#include 
#include 

#define DEBUG(va         


        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-28 12:43

    When you ask for fib(91) to give a value to your const fib91 in the source code, the compiler is forced to compute that value from you const expr. It does not compile the function (as you seem to think), just it sees that to compute fib91 it needs fib(90) and fib(89), to compute the it needs fib(87)... so on until he computes fib(1) which is given. This is an $O(n)$ algorithm and the result is computed fast enough.

    However when you ask to evaluate fib(45) in runtime the compiler has to choose wether using the actual function call or precompute the result. Eventually it decides to use the compiled function. Now, the compiled function must execute exactly the exponential algorithm that you have decided there is no way the compiler could implement memoization to optimize a recursive function (think about the need to allocate some cache and to understand how many values to keep and how to manage them between function calls).

提交回复
热议问题