3 ms·
> And then when it gets computed becomes an independent question from how it gets computed. You can update it eagerly, or lazily, or implicitly. You can use com
by choward 7y ago
> And then when it gets computed becomes an independent question from how it gets computed. You can update it eagerly, or lazily, or implicitly. You can use comparisons, or observables, or whatever.
But what about where distance is being used (read)? How do you know if updateDistance() got called already. It seems with this approach it would be important to still have a function for accessing it. But then that functions would need access to some sort of state that says whether or not the data is stale. Something like this:
let isDistanceStale = false;
let distance = 0;
let pos1 = { x: 0, y: 0, z: 0 };
let pos2 = { x: 0, y: 0, z: 0 };
function updatePos1(newPos1) {
pos1 = newPos1;
isDistanceStale = true;
}
function updatePos2(newPos2) {
pos2 = newPos2;
isDistanceStale = true;
}
function getDistance() {
if (isDistanceStale) {
distance = calculateDistance(pos1, pos2);
isDistanceStale = false;
return distance;
} else {
return distance;
}
}
function calculateDistance(a, b) {
return Math.sqrt(
(pos2.x - pos1.x) * (pos2.x - pos1.x) +
(pos2.y - pos1.y) * (pos2.y - pos1.y) +
(pos2.z - pos1.z) * (pos2.z - pos1.z));
}
Gross. This is why it's better not to made these kind of optimizations unless there really is a performance issue. Otherwise, just let it get computed every time or compute it every time pos1 or pos2 changes. No need to do lazy evaluation. If you really want that, there are languages that have it built in. Otherwise you'll just be fighting the language.
- brundolf 7y agoThe idea would be that you abstract it as a pure function and then you can layer on caching later, when you find out it's needed. The idea is not to always cache values, but to recognize when that's what you're doing and keep it separate from the rest of your state.