What's the fastest way to loop through an array in JavaScript?
After performing this test with most modern browsers:
https://jsben.ch/wY5fo
Currently, the fastest form of loop (and in my opinion the most syntactically obvious).
A standard for-loop with length caching
var i = 0, len = myArray.length;
while (i < len) {
// your code
i++
}
I would say, this is definitely a case where I applaud JavaScript engine developers. A runtime should be optimized for clarity, not cleverness.
What is the Fastest way of looping over an array on javascript?
Check this JavaScript loop benchmarks.
Fastest way to iterate through the oldest items in an array? (Fastest implementation of a queue)
The following is the FIFO queue implementation using singly linked list in javascript.
For more information of linked list -> https://www.geeksforgeeks.org/linked-list-set-1-introduction/
// queue implementation with linked list
var ListNode = function(val,next = null){
this.val = val
this.next = next
};
var Queue = function(){
let head = null;
let tail = null;
this.show = function(){
let curr = head;
let q = [];
while(curr){
q.push(curr.val);
curr = curr.next;
}
return q.join(' -> ');
}
this.enqueue = function(item){
let node = new ListNode(item);
if(!head) {
head = node;
tail = node;
} else {
tail.next = node;
tail = node;
}
}
this.dequeue = function(){
if(!head) return null;
else {
let first = head;
head = head.next;
first.next = null;
return first;
}
}
}
var myQueue = new Queue();
myQueue.enqueue(1); // head -> 1
console.log(myQueue.show())
myQueue.enqueue(2); // head -> 1 -> 2
console.log(myQueue.show())
myQueue.enqueue(3); // head -> 1 -> 2 -> 3
console.log(myQueue.show())
myQueue.dequeue(); // head -> 2 -> 3
console.log(myQueue.show())
fastest way to loop through an array
Modern day browsers support Array indexOf.
For the people saying the array indexOf is slower, basic tests on speed.
var values = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
console.time("for");
for(var i=0;i<1000;i++){
for(var j=0;j<=values.length;j++){
if(values[j]===20) break;
}
}
console.timeEnd("for");
console.time("reverse for");
for(i=0;i<1000;i++){
for(var j=values.length-1;j>=0;j--){
if(values[j]===1) break;
}
}
console.timeEnd("reverse for");
console.time("while");
for(i=0;i<1000;i++){
var j=0;
while (j<values.length){
if(values[j]===20) break;
j++;
}
}
console.timeEnd("while");
console.time("reverse while");
for(i=0;i<1000;i++){
var j=values.length-1;
while (j>=0){
if(values[j]===1) break;
j--;
}
}
console.timeEnd("reverse while");
console.time("indexOf");
for(var i=0;i<1000;i++){
var x = values.indexOf(20);
}
console.timeEnd("indexOf");
console.time("toString reg exp");
for(var i=0;i<1000;i++){
var x = (/(,|^)20(,|$)/).test(values.toString);
}
console.timeEnd("toString reg exp");
Two possible solutions:
var relatedVideosArray = [
["1047694110001"],
["1047694111001", "1019385098001","1020367665001","1020367662001", "1019385097001", "1020367667001"],
["1040885813001"],
["1019385094001", "1019385096001"],
["952541791001", "952544511001", "952544512001", "952544508001", "952541790001","952580933001", "952580934001", "1051906367001"]
]
//var getCurrentId = "1019385098001";
var getCurrentId = "1040885813001";
console.time("indexOf");
var tempStoreArray = [];
for(var i = relatedVideosArray.length-1; i>=0; i--){
var subArr = relatedVideosArray[i];
if(subArr.indexOf(getCurrentId)!==-1){
tempStoreArray.push(subArr);
}
}
console.timeEnd("indexOf");
console.log(tempStoreArray);
console.time("toString reg exp");
var tempStoreArray = [];
var re = new RegExp("(,|^)" + getCurrentId + "(,|$)");
for(var i = relatedVideosArray.length-1; i>=0; i--){
var subArr = relatedVideosArray[i];
if(re.test(subArr.toString())){
tempStoreArray.push(subArr);
}
}
console.timeEnd("toString reg exp");
console.log(tempStoreArray);
Fastest way to loop through Map keys
I created a JSBench with the methods. These are the results from fastest to slowest:
Map.prototype.forEach()
- Create array from
Map.prototype.keys()
and thenArray.prototype.forEach()
for of
loop throughMap.prototype.keys()
for of
loop throughMap.prototype[Symbol.iterator]()
Related Topics
Firing Event on Dom Attribute Change
Prevent a Webpage from Navigating Away Using JavaScript
How to Implement Routereusestrategy Shoulddetach for Specific Routes in Angular 2
Filter Array of Objects with Another Array of Objects
How to Make Div Fixed After You Scroll to That Div
How to Export HTML Table to Excel Using JavaScript
Setting Href Attribute at Runtime
Dashed Border Animation in CSS3 Animation
Formdata.Append("Key", "Value") Is Not Working
How Does Basic Object/Function Chaining Work in JavaScript
How to Mock an Es6 Module Import Using Jest
Browser-Native JSON Support (Window.JSON)
Execcommand() Is Now Obsolete, What's the Alternative
Use Functions Defined in Es6 Module Directly in HTML
Trigger Standard HTML5 Validation (Form) Without Using Submit Button