Caching is generally faster for any computation that is even somewhat complex, but there's a trade-off involved. By caching the results of your computation, you have to take some responsibility for invalidating the cache when the result of the computation is no longer accurate. Take the following example:
public class Rectangle
private int _height;
public int getHeight() {
return _height;
}
public void setHeight(int value) {
_height = value;
}
private int _width;
public int getWidth() {
return _width;
}
public void setWidth(int value) {
_width = value;
}
private int _area;
public int getArea() {
if (_area == 0) {
_area = _width * height;
}
return _area;
}
}
Here, the area calculation is stored so it doesn't need to be recomputed (this is a bit of a trivial example, and multiplications aren't really costly enough to justify caching, but you get the drift.). The following code works fine:
Rectangle r = new Rectangle();
r.setHeight(5);
r.setWidth(5);
r.getArea(); // returns 25.
But if we modify any of the information used to calculate the cached item, the code has a bug:
r.setHeight(3);
r.getArea(); // returns 25 - should be 15!
In this case the solution is easy - reset the area whenever height or width is set. But if your calculations become more complex, the calculations depend on something outside a single class, or your caching mechanism is more complex than a simple member variable, it can become somewhat troublesome to manage your caches.
In general, whenever you decide you want to use caching, you should proceed with caution and unit test heavily to ensure you're not introducing bugs.