I'm working in JavaScript native project where I have a huge array with 50k elements (json objects).
When i loop through this array it take a huge time > 2h
for(var i = 1; i <= myArray.length; i++) {
// my code here for each element
}
So what I plan to do is loop through specific indexes in array:
// loop one from index 0 to 10k
// loop one from index 10k to 20k
...
Each loop I will make it in a separate process
-
1Why not use two loops the second one starting at 10k?Tristanisginger– Tristanisginger2021年04月02日 13:24:07 +00:00Commented Apr 2, 2021 at 13:24
-
What type of content you are having in your JSON?Gyanesh Sharma– Gyanesh Sharma2021年04月02日 13:25:33 +00:00Commented Apr 2, 2021 at 13:25
-
hello @Tristanisginger sorry didn't get your idea. can you gave me an example pleaseJames– James2021年04月02日 13:25:37 +00:00Commented Apr 2, 2021 at 13:25
-
@gyaneshsharma yaes 50k json objects..James– James2021年04月02日 13:26:05 +00:00Commented Apr 2, 2021 at 13:26
-
"each loop i will make it in a separate process..." – Look up Web Workers for parallel processing.GG.– GG.2021年04月02日 13:26:43 +00:00Commented Apr 2, 2021 at 13:26
1 Answer 1
If you're just wanting to loop through specific indexes, would this work?
Using Math.min ensures that even when progressing in 10k increments, you never exceed the length of the array. With an array of 24736 items, the first loop would run from 0 to 9999, the second loop would run from 10000 to 19999, and the third loop would run from 20000 to 24736.
for(let i = 0; i < Math.min(myArray.length, 10000); i++) {
// ...
}
for(let i = 10000; i < Math.min(myArray.length, 20000); i++) {
// ...
}
for(let i = 20000; i < Math.min(myArray.length, 30000); i++) {
// ...
}
You can even nest these loops to perform actions between each loop, like this:
const myArray = Array(54723).fill();
for (let n = 0; n < myArray.length; n += 10000) {
for(let i = 0; i < Math.min(myArray.length, 10000); i++) {
// ...
}
console.log(Math.min(myArray.length, n + 10000));
}