I was recently facing a similar problem, where I needed to do some calculation in every frame and add it to a total from the previous frame. The problem with looping through every frame to the current one in every frame is the render becomes increasingly painful for the machine in every frame.
My solution was to make all the calculations on a text layer, in the first frame: I loop through all the frames, push the value of every frame to an array, and print the array as the Source Text. Someting like this:
mSource = thisComp.layer("source layer");
if (time == mSource.inPoint) {
totalValue = 0
values = [0];
for (i=timeToFrames(mSource.inPoint); i
Then, wherever the value has to appear, I pick the text from the first frame, split it by comma to create an array and pick the index corresponding to the frame I'm at:
mSource = thisComp.layer("source layer");
arr = thisComp.layer("text layer").text.sourceText.valueAtTime(mSource.inPoint);
mIndex = timeToFrames(time - mSource.inPoint);
val = arr.split(',')[mIndex];
val
The difference in rendering speed is night and day.