Frequently Asked Questions > Writing Better and Faster Scripts > How To Make It Faster? >

# Recursive functions can be faster

MAXScript FAQ > How To Make It Faster > Recursive functions can be faster

A recursive function is a function that calls itself in order to perform repetitive tasks.

The following scripted function returns a list of the animated subAnims of the object passed as parameter. The script works well and is not too slow.

NON-RECURSIVE VERSION
    fn getAllAnimatedProperties theObject =
    (
      scan_properties = #(theObject)
      animated_props = #()
      cnt = 0
      while cnt < scan_properties.count do
      (
        cnt +=1
        currentObj = scan_properties[cnt]
        if try (currentObj.isAnimated) catch (false) do
          append animated_props currentObj
        for i = 1 to currentObj.numSubs do
          append scan_properties currentObj[i]
      )
      animated_props
    )
    getAllAnimatedProperties $

Now take a look at this code:

RECURSIVE VERSION
    animated_props = #()
    fn getAnimatedProps theObject =
    (
      if try (theObject.isAnimated) catch (false) do
        append animated_props theObject
      for i = 1to theObject.numSubs do
        getAnimatedProps theObject[i]
    )
    getAnimatedProps $

The recursive code does the same job, but is much shorter and almost 25% faster! (In order to get some usable measurement, both scripts were executed 100,000 times - the first took 13.875 seconds, the recursive version only 10.656 seconds.

Previous Tip

Pre-initialize arrays when final size is known

Next Tip

matchPattern is faster than findString