Fast.js JavaScript Versions Of Built-In Functions Are Faster |
Written by Ian Elliot |
Tuesday, 01 July 2014 |
Just to demonstrate how all grown up JavaScript is, Fast.js re-implements a number of built-in native functions in JavaScript. Guess what - they are faster!
There used to be a basic rule that in a language like JavaScript built-in functions ware always much faster than the equivalent code expressed in the raw language. The reason was fairly obvious - the built-in functions were coded in native code, whatever that might be, and you were comparing compiled versus interpreted. However, over time and with advanced JIT compilers and optimization techniques, JavaScript has got faster. So fast that the trusted rule no longer seems to apply, or does it?
Fast.js is an open source library that provides implementations of .foreach, .map, .reduce, concat, bind, apply, filter, indexOf and LastIndexOf. It also implements two standard utility functions - partial and clone, which are not built in - in a fast style and it provides an alternative for try as a fast function.
Some of the functions are simply faster versions, but some make simplifying assumptions to provide even more speed. For example, the built-in map, reduce and foreach functions have to cope with the possibility that the array that they are being used with is sparse. The example given in the documentation is:
In this case there is only one used element in the array and the built-in function forEach only calls logIt once. The fast alternative assumes that all arrays are completely used, i.e. non-sparse, and it can avoid having to do the test that the built-in function has to perform. For example:
The payoff for not handling sparse arrays is that the fast function is up to five times faster. Other functions in the library are similarly optimized for the most common use cases - consult the documentation for more information. You can also find a benchmark which you can use to see if it is worth using the fast versions in your production environment. The gains vary according to the function, but can be anything from a modest 30% to an unlikely sounding 3650% improvement.
More InformationRelated ArticlesJava, ASM.js Or Native - Which Is Faster?
To be informed about new articles on I Programmer, install the I Programmer Toolbar, subscribe to the RSS feed, follow us on, Twitter, Facebook, Google+ or Linkedin, or sign up for our weekly newsletter.
Comments
or email your comment to: comments@i-programmer.info
|
Last Updated ( Tuesday, 01 July 2014 ) |