Home / Updating an existing average with a new value (for DB cache)
Node JS

Updating an existing average with a new value (for DB cache)

Calculating averages can be an expensive operation. Say you have 10 million customer database records and you want to keep track of the average age of your customers. <!–more–> You can either:

  • Recalculate the average everytime it is required, accessing all 10 million database records and summing them up in the process, or;
  • Cache an average and update it every time a new customer is added to the database.

This equation is what you need:

$${{a}_{new}}{=}{\frac {nr+x} {n+1}}$$

Where n is the number of records, a is the current average and r is the new value to be added.

Continue your adventure here

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More

DON’T MISS OUT!
Subscribe To Newsletter
Be the first to get latest updates and exclusive content straight to your email inbox.
Stay Updated
Give it a try, you can unsubscribe anytime.
close-link