Optimizing by caching states