Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>It doesn't make sense to compare very, very inefficient code. When you do you are comparing very specific optimisations the languages do which give you little indication which a different program might do.</p> <hr> <p>Your solution is very slow in Java and JavaScript. Some languages are smart enough to re-write your code more efficiently (e.g. functional languages) but neither Java nor JavaScript will re-organise you code to be more efficient.</p> <pre><code>private static int fib(int n) { return n &lt;= 1 ? n : fib(n - 1) + fib(n - 2); } </code></pre> <p>Think about this, to get a solution of 1134903170, you need to call this method more than this many times (to get down to 1 and all the calls down to those values)</p> <p>Note: each solution takes exponentially longer and is proportional to the solution.</p> <p>I suggest you use iteration which is much faster in Java and JavaScript.</p> <pre><code>private static long fib(int n) { long a = 1, b = 1; while (--n &gt; 1) { long c = a + b; a = b; b = c; } return b; } </code></pre> <p>Note: the time this take is proportional to the value of <code>n</code>, in this case 45.</p> <p>Note 2: this solution is so short, the code doesn't even warmup and get compiled by the JIT.</p> <pre><code>public static void main(String... ignore) { for (int j = 0; j &lt; 5; j++) { long fib = 0, start = System.nanoTime(); int repeats = 2000; for (int i = 0; i &lt; repeats; i++) fib = fib(45); long avgTime = (System.nanoTime() - start) / repeats; System.out.println(fib + " took an average of " + avgTime + " nano-seconds"); } } </code></pre> <p>prints</p> <pre><code>1134903170 took an average of 2695 nano-seconds 1134903170 took an average of 995 nano-seconds 1134903170 took an average of 90 nano-seconds 1134903170 took an average of 89 nano-seconds 1134903170 took an average of 89 nano-seconds </code></pre> <p>Note 3: The 89 nano-seconds is ~4 billion times faster, which cannot be explained by using a faster machine.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload