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

# Pre-initialize arrays when final size is known

MAXScript FAQ > How To Make It Faster > Pre-initialize arrays when final size is known

When adding elements to an array using the append method, a copy of the original array is being created in memory before the new array is created. When the size of an array is known before the array is actually used, it is a good practice to pre-initialize the array in memory by assigning the last element of the array to some temporary value. This will create an array of the desired size in memory and will let you simply assign values to any element of the array using indexed access without the memory overhead of the append method.

FOR EXAMPLE, INSTEAD OF USING SOMETHING LIKE
    MyArray = #()--creates an empty array
    for i = 1 to 100 do
      append MyArray (random 1 100)--append each element

YOU CAN USE
    MyArray = #()
    MyArray[100] = 0--initialize a 100 elements array in memory
    for i = 1 to 100 do
      MyArray[i] = random 1 100--assign to predefined array

Previous Tip

Use bitArrays instead of Arrays when possible

Next Tip

Recursive functions can be faster