1

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?

Barmar
  • 741,623
  • 53
  • 500
  • 612
KoulJak
  • 105
  • 8
  • 3
    You could start by using `Object.values()` since you're not doing anything with the key. – Barmar Mar 02 '22 at 17:26
  • 1
    If the data doesn't change, you can cache it. If it does, then you won't be able to achieve a large speedup. (You could make the provider of the data keep track of these stats, so you don't have to recompute it everytime.) – FZs Mar 02 '22 at 17:38

1 Answers1

0

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);
Socko
  • 665
  • 2
  • 9