Music 220b: Winter 2001
Fernando Lopez-Lezcano, instructor
Christopher Burns, teaching assistant
Tamara Smyth, teaching assistant
Week 3: arrays v. lists
Now that we know about arrays and lists, when should we use one or the other? Here are some pointers....
You can use either arrays or lists inside of a CLM instrument's run loop. However, all other things being equal, a run loop using an array will execute more quickly than one using a list. This is because the run loop is compiled to C -- where arrays are more efficiently implemented than lists. (Why does efficiency matter? Because you'll have to execute the code in the run loop thousands of times over for every second of sound you render). So there's an easy rule of thumb: if your data structure will appear in the run loop, make it an array.
The other advantage of arrays is that it's quite a bit easier to access elements from a multidimensional array than from an equivalent list. The (aref) function scales smoothly to multiple dimensions, while we have to use a new instance of the (nth) function for each nesting of a list inside of a list. For instance, consider the following two equivalent functions:
(let* ((test-array (make-array (list 3 3) :initial-contents (list (list 1 2 3) (list 4 5 6) (list 7 8 9))))) (+ (aref test-array 0 0) (aref test-array 2 2)))
(let* ((test-list (list (list 1 2 3) (list 4 5 6) (list 7 8 9)))) (+ (nth 0 (nth 0 test-list)) (nth 2 (nth 2 test-list))))
The array is more complicated to construct, but easier to access.
Lists also have a variety of attractive features. For one thing, they're totally native to Lisp -- so there are lots of friendly functions like (length), (append), (first), (last) and many others. (See the Steele chapter on lists for details).
Secondly, lists can easily be resized on the fly. (So can arrays, but it takes more work). Here's a three-element list in the process of becoming a five-element list:
(setf test-list-2 '(1 2 3)) (setf test-list-2 (append test-list-2 '(4 5)))
Finally, lists can have very complex structures:
(list 1 2 3 (list 4 5 (list 6) 6) 4 5 (list 6 7 (list 8) 8) 6 7 8)
Outside of the run loop, lists are frequently your best bet....
Course resources main page
220b main page