2011年12月4日 星期日

Maxscript : Writing Better and Faster Scripts


( Frequently Asked Questions in MAXscript help)

Disable Viewport Redraws when making changes to scene objects
You can use the with redraw off() context or a pair of disableSceneRedraw() and enableSceneRedraw() calls to speed up you code. The former method is the preferred one.

Disable Undo system when possible
ondo off( ... ) ; ondo on( ... ) ; with undo off
print (et-st) --print the resulting time
gc() --call Garbage Collection &endash; you will needed it!

Modify Panel can be slow - change to Create Panel when possible
In 3ds Max 7 and higher, you can also completely disable Modify Panel updates using the suspendEditing() and resumeEditing() methods

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

Cache frequently used functions and objects
You can store frequently used functions and objects in user variables to faster access.

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.

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


matchPattern is faster than findString
When searching for a substring inside a string, using the matchPattern() method is faster than using findString().
Executing the same method one million times on the same PC resulted in:
3.7 seconds execution time for matchPattern
5.9 seconds execution time for findString
5.0 seconds execution time for subString when comparing the first 3 characters.

Do not use return, break, exit or continue

Return, break, exit, continue and throw are implemented using C++ exception.
C++ exceptions are SLOW!

Use StringStream to build large strings
If building strings, use a StringStream value to accumulate the string and then convert to a string.

fn test5d =
(
 local ss = stringstream"",fmt ="%"
 for i = 1 to 100 do format fmt ito:ss
 ss as string
)

Using Bsearch For Fast Table Lookup
The bsearch() method available in 3ds Max 2009 and higher allows for very fast table lookup operations in sorted arrays.

沒有留言:

張貼留言