Is this a good way to cache results from pure functions?

Just learnt pure functions are called for every node its output is connected to.

Observe below. One could expect the same random float to be printed twice:


But since the function is called twice, the two floats printed are different.

So here’s a workaround that occurred to me, make a non-pure function that does nothing but cache results.
blueprint question 00


With this, the two printed floats are indeed identical numbers.

My questions is, is this a good practice to adhere to? Any downside I don’t know of? Also is it really true the compiler just have pure functions run for every node and doesn’t do any optimization at all? (I have SO MANY blueprints to go over and refactor if that’s the case…)

You could also just put it in a variable

Pure functions always evaluate for every call by design. Otherwise, you could be here wondering why the function doesn’t re-evaluate when you’ve changed something between calls :slight_smile:

when

I don’t want to litter my blueprints with tons of 1 time use variables. If I reuse them, I run the risk of the variables being used concurrently elsewhere, causing unexpected behaviors.

And good point! Guess I can’t avoid redoing a bunch of blueprints then…

Why not use a local variable?

I don’t want to litter my blueprints with tons of 1 time use variables.

So you’ll litter them with 1 time use functions instead? :eyes:

1 Like

If I’m working inside a function, sure I’ll use local variables. This is for outside functions, in event graph.

And no, I’ll just make a cache function for each of the main variables (bool, byte, int, float, etc.) in a blueprint library. Then they can be popped basically anywhere.

For functions with multiple outputs, I’ll still have to basically wrap them in another function.
wrapped function
But at least for all the single output pure functions, I have an easy way to cache their results (without making a bunch of duplicate functions, which I’ll have to maintain by making sure their input variables and default variables are synced.).

I’ve discovered an easy solution in the form of a macro:

Here’s an example usage:

The “Cached” pin value is now the same irrespective of when the timeline gets updated again.