IDL programming for Speed and Memory Management
The techniques demonstrated here all apply to MatLab as well as IDL, and most apply for any programming Language.
speedtest.pro - a set of demonstrations of how to write code that executes faster. The amount of system time taken for each demonstration is displayed. You can copy and save the text into a file with the '.pro' extension, then run it on your own computer. For each circumstance the slower running code is exhibited first, followed by an example of how to speed it up.
sub_memory.pro - examples of how to conserve memory while passing large variable arrays to subroutines. Normally a copy of each variable passed remains in main memory while a copy is made for the subroutine, doubling the memory usage (or even more if the subroutine passes the variable to another subroutine). There are two ways to avoid this copying of passed variables:
- Common Blocks - you may create a named list of variables which reside in a common memory accessed by all subroutines. This is the simplest way to avoid redundant copies of variables in memory. The drawback is that you are forced to use exactly the same variable names throughout the set of subroutines, reducing portability to other programs.
- Pointer Variables - once a variable is created it can be copied to a common memory space called heap memory. The address of the location in heap memory is called a 'pointer', and can be passed as a short variable that references the much larger array you've put into heap memory. For this to conserve memory you must then destroy the original variable. From then on you pass the pointer variable, and use the '*' operator to access the full variable in memory. Since you can change the name of the pointer variable this form is more portable, but the mechanics of creating and referencing the pointer adds a little complexity and reduces readability.