EDIT: apparently I asked this question wrong. Before voting to close, please allow me to know what the question is missing. I promise you, this is not an unanswerable question. You can always come back and vote to close it later.
I'm currently working in C++, but I think this question applies to most compiled languages.
In my project, I have an array of values which are calculated individually, one at a time, as late as possible based off a single variable. These values are not all calculated at once, they are calculated if and only if they need to be. As is normally the case when using "dirty", the objective is to label certain things as being in need of update, without updating it preemptively. These values are cycled through over and over, so I'd like to cache the computation if possible. Whenever the single variable changes, all the values should be marked dirty so the cycle knows to recalculate before storing and moving on.
I can think of a few ways of achieving this, but I'm not sure what is most efficient:
- Have two arrays, one of booleans and one of values. Mark all booleans to false if dirty, and true when clean.
- Have a clean start point. Consider everything dirty until passing that cycle point again. Has the drawback of not allowing skipping of cycle entries.
- Brand new array. Just create a new array, if any of the items are unset, set them. This one seems like it would have tons of problems, but it's a thought.
- Perhaps use some built in class meant for this stuff?
The above are just the first things that came to mind for me, but I'm kind of new to c++ and would like to have some idea of normal or special solutions to marking an array dirty.
How can I dirty an array efficiently?
In order to show an example of code, I will show js which I'm more used to:
const numbers = [];
const clean = [];
let length = 1000;
let variable;
const setVariable(num) => {
variable = num;
for (let i = 0; i < length; i++) { clean[i] = false; }
}
setVariable(42);
let pos = 0;
while (true) {
if (clean[pos] == false) {
clean[pos] = true;
numbers[pos] = someIntensiveMath(pos, variable);
}
doSomethingWithNumbers(numbers[pos]);
pos++;
if (pos >= length) pos = 0;
// wait a bit;
}
in js you could also do
const setVariable(num) => {
variable = num;
numbers = [];
}
const isDirt = numbers[pos] === undefined;
With js the latter would probably be faster due to the native implementation of the script, but I don't think that's the case with compiled languages. I think you guys do things differently.