JavaScript: Get the index of the function in an array of functions which executed the fastest
JavaScript fundamental (ES6 Syntax): Exercise-175 with Solution
Write a JavaScript program to get the index of the function in an array of functions which executed the fastest.
- Use Array.prototype.map() to generate an array where each value is the total time taken to execute the function after iterations times.
- Use the difference in performance.now() values before and after to get the total time in milliseconds to a high degree of accuracy.
- Use Math.min() to find the minimum execution time, and return the index of that shortest time which corresponds to the index of the most performant function.
- Omit the second argument, iterations, to use a default of 10000 iterations.
- The more iterations, the more reliable the result but the longer it will take.
Sample Solution:
JavaScript Code:
// Define a function 'mostPerformant' that takes an array of functions 'fns' and an optional parameter 'iterations' with a default value of 10000
const mostPerformant = (fns, iterations = 10000) => {
// Map each function in 'fns' to its execution time in milliseconds
const times = fns.map(fn => {
// Record the current timestamp in milliseconds before executing the function
const before = performance.now();
// Execute the function 'iterations' number of times
for (let i = 0; i < iterations; i++) fn();
// Calculate the elapsed time by subtracting the start time from the current time
return performance.now() - before;
});
// Find the index of the minimum time in the 'times' array and return it
return times.indexOf(Math.min(...times));
};
// Log the index of the most performant function among the provided functions
console.log(mostPerformant([
// First function: Loops through the entire array before returning `false`
() => {
[1, 2, 3, 4, 5, 6, 7, 8, 9, '10'].every(el => typeof el === 'number');
},
// Second function: Only needs to reach index `1` before returning false
() => {
[1, '2', 3, 4, 5, 6, 7, 8, 9, 10].every(el => typeof el === 'number');
}
])); // 1
Output:
1
Flowchart:
Live Demo:
See the Pen javascript-basic-exercise-174-1 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus
Previous: Write a JavaScript program to convert a NodeList to an array.
Next: Write a JavaScript program to get the n minimum elements from the provided array.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/javascript-exercises/fundamental/javascript-fundamental-exercise-175.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics