Editing Factorial cache This edit will create a new revision. Your details (optional) Name Email (won’t be displayed; might be used for Gravatar) URL Test case details Title * Published (uncheck if you want to fiddle around before making the page public) Description (in case you feel further explanation is needed)(Markdown syntax is allowed) some more methods Are you a spammer? (just answer the question) Preparation code Preparation code HTML (this will be inserted in the <body> of a valid HTML5 document in standards mode) (useful when testing DOM operations or including libraries) Obviously caching wins. <script> function factorial(n) { if (n < 1) return 1; else return n * factorial(n - 1); } function factorial2(n) { factorial2.cache = factorial2.cache || [1]; return factorial2.cache[n] || (factorial2.cache[n] = n * factorial2(n - 1)); } function factorial3(n) { var res = 1; for (var i = 2; i <= n; ++i) res = res * i; return res; } function factorial4(n){ var j = n; while (--j) { n *= j; } return n; } function factorial5(n){ for (var j = n-1; j > 1; j--) { n *= j; } return n; } function factorial5b(n){ for (var j = n; j > 1; --j) { n *= j; } return n; } function factorial5c(n){ for (var j = n; j > 1; --j) { n = n * j; } return n; } function factorial5_cache(n){ if(! this.cache) this.cache = [1]; if(! this.cache[n] ) { var n0 = n; for (var j = n0-1; j > 1; j--) { n0 *= j; } this.cache[n] = n0; } return this.cache[n]; } var n; </script> <p>Do they work?</p> <script> // do they work? n = 7; document.write( factorial(n) == factorial2(n) ? "YES" : "NO" ); document.write( factorial(n) == factorial3(n) ? "YES" : "NO" ); document.write( factorial(n) == factorial4(n) ? "YES" : "NO" ); document.write( factorial(n) == factorial5(n) ? "YES" : "NO" ); </script> Include JavaScript libraries as follows: <script src="//cdn.ext/library.js"></script> Define setup for all tests (variables, functions, arrays or other objects that will be used in the tests) (runs before each clocked test loop, outside of the timed code region) (e.g. define local test variables, reset global variables, clear canvas, etc.) (see FAQ) n = Math.floor(Math.random() * 170); Define teardown for all tests (runs after each clocked test loop, outside of the timed code region) (see FAQ) Code snippets to compare Test 1 Title Async (check if this is an asynchronous test) Code factorial(n); Test 2 Title Async (check if this is an asynchronous test) Code factorial2(n); Test 3 Title Async (check if this is an asynchronous test) Code factorial3(n); Test 4 Title Async (check if this is an asynchronous test) Code factorial4(n); Test 5 Title Async (check if this is an asynchronous test) Code factorial5(n); Test 6 Title Async (check if this is an asynchronous test) Code factorial5b(n); Test 7 Title Async (check if this is an asynchronous test) Code factorial5_cache(n);