The Mathematica Journal
Feature Articles
New Products
New Publications
News Bulletins
Write Us
About the Journal
Staff and Contributors
Back Issues
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.


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


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


The speed advantage typically comes in common operations.


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]