Only calculate once if possible

MAXScript FAQ > How To Make It Faster > Only calculate once if possible

MAXScript does no code optimization. You must do your own optimizations.

Try to avoid running the same calculation more than once, or interrogating the same value in the same node more than once.

TEST CASE:

fn test4a inVal =
(
local res = 0
for i = 1 to 100 do res += ((inVal * 10) + i)
res
)
--show the same nice black-red gradient 
fn test4b inVal =
(
local res = 0
local temp = inVal * 10
for i = 1 to 100 do res += (temp + i)
res
)

FOR 100,000 ITERATIONS:

test4a 0   -- 20562 msec.
test4b 0   -- 17797 msec. 

In another example, a typical example of a script that you want to be as fast as possible is a Particle Flow Script Operator. In a typical Script Operator, you usually go through all particles in the Particle Container of the current Event and perform some operations on each one of them.

The Proceed handler typically looks like

GOOD CODE:

on Proceed pCont do
(
count = pCont.NumParticles()
for i in 1 to count do
(
pCont.particleIndex = i
pCont.particleVector = pCont.ParticlePosition
)
)

Note that the variable 'count', containing the number of particles to be processed, is evaluated only once and then used as the top limit of the i loop.

Writing the same as

BAD CODE:

on Proceed pCont do
(
for i in 1 to pCont.NumParticles() do
(
pCont.particleIndex = i
pCont.particleVector = pCont.ParticlePosition
)
)

would be a bad idea, because in the case of 1 million particles, the expression pCont.NumParticles() will be evaluated 1 million times instead of just once!

Previous Tip

Never get a single pixel when you can get a whole line

Next Tip

Cache freqeuntly used functions and objects