Tuesday, August 5, 2008

In place Array methods for Prototype


Unlike Ruby, Prototype does not offer in place iterators for Array methods such as compact, map and reject. I started down the road of implementing these methods, and discovered significant improvements with large arrays. Since Javascript does not support the "!" character in function names, I decided to name the in place versions with underscore prefixes.

map

_map is simple to implement. We replace the value in each index with the result of the iterator function:


In this case, and the remaining ones, this is returned so that the methods can be chained.

reject

For in place _reject, I scan the array once from left to right. Elements that are not rejected are placed in the array from left to right, and finally the length is truncated. I believe it is important to maintain the original order of the elements:


compact

_compact is very similar to reject:


The above implementation can be shortened by using _reject, but it significantly reduces performance. For completeness, that might be written as:


Results

These are results in Firefox 3, using an array of 100,000 numbers and null values. Changing the size did not seem to affect the relative performance.
MethodPrototype TimeIn Place Time
map159ms42ms
reject158ms45ms
compact161ms13ms

One should probably do a more comprehensive test, but these results are enough to show that performance gains can be made with my faster versions. In addition, less memory is being used.


0 comments: