'How to improve forEach in JavaScript for large lists
I have a pretty big data object and every time I refresh the page I have to resume the data from that water. Is there a way I can make a forEach faster?
if (Object.keys(jsonData.data.users).length > 0) {
Object.keys(jsonData.data.users).forEach((username) => {
const user = jsonData.data.users[username];
const register_date = new Date(user.register_date);
if (register_date >= start_date && register_date <= end_date) {
data.guestsNumber++;
}
actions += user.actions_per_session;
session_duration += user.session_duration;
data.cartViews += user.cart_views;
})
data.actionsPerSession = (actions / (Object.keys(jsonData.data.users).length)).toFixed(2);
data.averageSessionDuration = (session_duration / (Object.keys(jsonData.data.users).length)).toFixed(2);
}
What ways would there be to give a better time?
Solution 1:[1]
In general, this looks sufficiently fast. You can take some benchmarks via jsbench.me, but I think you're going to have to look beyond the code to re-architecting overall page load times.
But here's how I'd refactor the code to squeeze out performance
You can convert if (arr.length > 0) { arr.forEach(...) } to just do arr.forEach(...). If the array is empty, forEach will just never fire the callback, but is still valid. That prevents doing Object.keys(jsonData.data.users) twice.
Also, you're calling Object.keys(jsonData.data.users) 4 different times; should be slightly faster to allocate to a variable and re-use that.
So should look like this:
var users = Object.keys(jsonData.data.users);
users.forEach((username) => {
const user = jsonData.data.users[username];
const register_date = new Date(user.register_date);
if (register_date >= start_date && register_date <= end_date) {
data.guestsNumber++;
}
actions += user.actions_per_session;
session_duration += user.session_duration;
data.cartViews += user.cart_views;
})
data.actionsPerSession = (actions / (users.length)).toFixed(2);
data.averageSessionDuration = (session_duration / (users.length)).toFixed(2);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Socko |
