Fibonacci sequense sum algorithms

JavaScript performance comparison

Revision 8 of this test case created by dmi3y

Preparation code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
      
<script>
Benchmark.prototype.setup = function() {
  var n = 60;
  
  function _fibSum(f, s, n) {
    fs = f + s;
    return n-- > 2? fs + _fibSum(s, fs, n): ++fs;
  };

};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
recurcing function
(function fibSum(n){
  var fibsum = (function _fibSum(n, f, s) {
        return n > 2? f + s + _fibSum((n - 1), s, (f + s)): f + s + 1;
      }(n, 0, 1));
  return fibsum;
}(n));
pending…
plain cycle
(function fibSum(n) {
  var sum = 0,
      cur,
      prev = 0,
      prevprev = 0;
  for(; n--;) {
    cur = prev + prevprev || 1;
    prevprev = prev;
    prev = cur;
    sum += cur;
  }
  return sum;
}(n));
pending…
optimized recursive
(function fibSum(n){
  var fs;
  return (function _fibSum(f, s) {
        fs = f + s;
        return n-- > 2? fs + _fibSum(s, fs): ++fs;
      }(0, 1));
}(n));
pending…
outer function call
(function fibSum(n){
  var fs;
  return _fibSum(0, 1, n);
}(n))
pending…
one step optimized, optimized recursive
(function fibSum(n){
  var fs;
  return (function _fibSum(f, s) {
        fs = f + s;
        return n-- > 3? fs + _fibSum(s, fs): fs + 2;
      }(1, 1));
}(n))
pending…
plain while
(function fibSum(n) {
  var sum = 0,
      cur,
      prev = 0,
      prevprev = 0;
  while(n--) {
    cur = prev + prevprev || 1;
    prevprev = prev;
    prev = cur;
    sum += cur;
  }
  return sum;
}(n));
pending…
formula from http://milan.milanovic.org/math/english/sum/fibsum.html
(function term(s) {
	var k=0, n=s, f, t;
	 {
		
		f=Math.round((Math.pow((1+Math.sqrt(5))/2,n)*Math.pow((1+Math.sqrt(5))/2,2)
		-Math.pow((1-Math.sqrt(5))/2,n)*Math.pow((1-Math.sqrt(5))/2,2))/Math.sqrt(5))
		-Math.round((Math.pow((1+Math.sqrt(5))/2,k)*Math.pow((1+Math.sqrt(5))/2,1)
		-Math.pow((1-Math.sqrt(5))/2,k)*Math.pow((1-Math.sqrt(5))/2,1))/Math.sqrt(5));
		if(f=="Infinity") t="too big for JavaScript";
		else t=f;
		
		return t;
	}
}(n))
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL.

0 Comments