Main Content

Caching results in an object for efficiency - avoiding re-calculation

Archive - Originally posted on "The Horse's Mouth" - 2016-01-20 17:04:35 - Graham Ellis

Do you like to do the same thing time and time and time again? Probably not, as it's boring and inefficient. Computers don't get bored, but they can be inefficient if not programed well ... and because they don't get bored, they don't complain if they're inefficient.

Imagine you have a class of objects on which you need to perform a complex calculation.

Scenario 1 ... you create 100 objects but only need the calculation results from 10 of them

Scenario 2 ... you create 5 objects and need the results from each of them 10 times over.

If you do the calculation as you enter data into the objects, you'll do 100 calculations in the first scenario and 5 in the second - total 105

If you do the calculatio as you get the results out, you'll do 10 calculations in the first scenario and 50 in the second - total 60

If you calculate the results just in time and store them in the object when calculates (cache the answer) you only need to make 10 calculations for the first scenario and 5 for the second - total 15.

Sample program - [here].