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.
| Method | Prototype Time | In Place Time |
|---|---|---|
| map | 159ms | 42ms |
| reject | 158ms | 45ms |
| compact | 161ms | 13ms |
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:
Post a Comment