Use Array Operations Whenever Possible
Whenever possible, vector and array data should always be processed with array operations instead of scalar operations in a loop. For example, consider the problem of inverting a 512-by-512 image. This problem arises because about half of the available image display devices consider the origin to be the lower-left corner of the screen, while the other half use the upper-left corner.
note | This example is for demonstration only. The system variable !Order should be used to control the origin of image devices. The Order keyword to the TV procedure serves the same purpose. |
A programmer without experience in using PV-WAVE might be tempted to write the following nested loop structure to solve this problem:
FOR I = 0, 511 DO FOR J = 0, 255 DO BEGIN
; Temporarily save pixel image.
TEMP = IMAGE (I, J)
; Exchange pixel in same column from corresponding row at
; bottom.
IMAGE(I, J) = IMAGE(I, 511 - J)
IMAGE(I, 511 - J) = TEMP
ENDFOR
Executing this code required 143 seconds.
A more efficient approach to this problem capitalizes on PV-WAVE’s ability to process arrays as a single entity.
FOR J = 0, 255 DO BEGIN
; Index of corresponding row at bottom.
SW = 511 - J
; Temporarily save current row.
TEMP = IMAGE(*, J)
; Exchange row with corresponding row at bottom.
IMAGE(0, J) = IMAGE(*, SW)
IMAGE(0, SW) = TEMP
ENDFOR
Executing this revised code required 11 seconds, which is 13 times faster.
At the cost of using twice as much memory, things can be simplified even further:
; Get a second array to hold inverted copy.
IMAGE2 = BYTARR(512, 512)
; Copy the rows from the bottom up.
FOR J = 0, 511 DO IMAGE2(0, J) = IMAGE(*, 511 - J)
This version also ran in 11 seconds.
Finally, using the built-in ROTATE function:
; Inverting image is equivalent to transposing it and rotating it
; 270o clockwise.
IMAGE = ROTATE(IMAGE, 7)
This simple statement took 0.6 seconds to execute.