 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Comparing the performance of recursive and looped factorial function in JavaScript
We will be writing two JavaScript functions, the job of both the functions will be to take in a number and return its factorial.
The first function should make use of a for loop or while loop to compute the factorial. Whereas the second function should compute the factorial using a recursive approach.
Lastly, we should compare the times taken by these functions over a large number of iterations.
Example
Following is the code −
const factorial = (num = 1) => {    let result = 1;    for (let i = 2; i <= num; i += 1) {       result *= i;    }    return result; } const factorialRecursive = (num = 1) => {    if(num > 1){       return num * factorialRecursive(num - 1);    }else{       return 1;    } }; const ITERATIONS = 100000000; const num = 12; console.time('Looping Approach'); for(let i = 0; i < ITERATIONS; i++){    factorial(num); }; console.timeEnd('Looping Approach'); console.time('Recursive Approach'); for(let j = 0; j < ITERATIONS; j++){    factorialRecursive(num); }; console.timeEnd('Recursive Approach');  Output
Following is the output on console −
Looping Approach: 886.720ms Recursive Approach: 6526.203ms
This time taken will vary from machine to machine by the ratio is bound to remain more or less the same.
Advertisements
 