benchmark.js (1822B)
1 // 2 // typed-function benchmark 3 // 4 // WARNING: be careful, these are micro-benchmarks, which can only be used 5 // to get an indication of the performance. Real performance and 6 // bottlenecks should be assessed in real world applications, 7 // not in micro-benchmarks. 8 // 9 // Before running, make sure you've installed the needed packages which 10 // are defined in the devDependencies of the project. 11 // 12 // To create a bundle: 13 // 14 // browserify -o benchmark/benchmark.bundle.js benchmark/benchmark.js 15 // 16 17 'use strict'; 18 19 var assert = require('assert'); 20 var Benchmark = require('benchmark'); 21 var padRight = require('pad-right'); 22 var typed = require('../typed-function'); 23 24 // expose on window when using bundled in a browser 25 if (typeof window !== 'undefined') { 26 window['Benchmark'] = Benchmark; 27 } 28 29 function add(x, y) { 30 return x + y; 31 } 32 33 var signatures = { 34 'number, number': add, 35 'boolean, boolean': add, 36 'Date, Date': add, 37 'string, string': add 38 }; 39 40 var addTyped = typed('add', signatures); 41 42 assert(add(2,3), 5); 43 assert(addTyped(2,3), 5); 44 assert(addTyped('hello', 'world'), 'helloworld'); 45 assert.throws(function () { addTyped(1) }, /TypeError/) 46 assert.throws(function () { addTyped(1,2,3) }, /TypeError/) 47 48 var result = 0; 49 var suite = new Benchmark.Suite(); 50 suite 51 .add(pad('typed add'), function() { 52 result += addTyped(result, 4); 53 result += addTyped(String(result), 'world').length; 54 }) 55 .add(pad('native add'), function() { 56 result += add(result, 4); 57 result += add(String(result), 'world').length; 58 }) 59 .on('cycle', function(event) { 60 console.log(String(event.target)); 61 }) 62 .on('complete', function() { 63 if (result > Infinity) { 64 console.log() 65 } 66 }) 67 .run(); 68 69 function pad (text) { 70 return padRight(text, 20, ' '); 71 }