The Mathematica Journal
Departments
Feature Articles
Columns
New Products
New Publications
Classifieds
Calendar
News Bulletins
Mailbox
Letters
Write Us
About the Journal
Staff and Contributors
Submissions
Subscriptions
Advertising
Back Issues
Home
Download this Issue


Advantages of Packed Arrays

There are two advantages of packed arrays: memory and speed. The memory is the most obvious of these.

[Graphics:../Images/index_gr_11.gif]
[Graphics:../Images/index_gr_12.gif]

If we change the first element to be a different type, the result cannot be stored as a packed array.

[Graphics:../Images/index_gr_13.gif]
[Graphics:../Images/index_gr_14.gif]

A list of reals takes about [Graphics:../Images/index_gr_15.gif]times as much memory as the corresponding packed array.

[Graphics:../Images/index_gr_16.gif]
[Graphics:../Images/index_gr_17.gif]

The speed advantage typically comes in common operations.

[Graphics:../Images/index_gr_18.gif]
[Graphics:../Images/index_gr_19.gif]
[Graphics:../Images/index_gr_20.gif]
[Graphics:../Images/index_gr_21.gif]

Understanding why the timing difference occurs is the key to knowing when packed arrays will help your code run faster.

In the first operation, a is stored as a packed array, so when Plus sees it, it knows that all of the elements are machine real numbers, and internally, a function that adds arrays of real numbers is added. Except for overflow and underflow checking that Mathematica does, this is done as fast as you could get by writing a loop to do the addition in a C-program for two arrays of machine numbers.

In the second operation, b is stored as List[...], so what happens is that first Plus is threaded over the lists, producing (roughly) {b[[1]] + b[[1]], b[[2]] + b[[2]], .... }.

That is, Plus has to process 1000 expressions. For each pair of numbers, Plus has to use the information attached to those numbers (i.e., real, integer, machine, bignum, etc.), to determine which function to use to do the actual adding. This all takes time and accounts for nearly all of the difference here.

There are different ways that packed arrays can speed things up, but this exemplifies the type which typically gives the greatest speedup.


Converted by Mathematica      May 1, 2000

[Article Index] [Prev Page][Next Page]