2 * Benchmark.js v1.0.0 <http://benchmarkjs.com/>
3 * Copyright 2010-2012 Mathias Bynens <http://mths.be/>
4 * Based on JSLitmus.js, copyright Robert Kieffer <http://broofa.com/>
5 * Modified by John-David Dalton <http://allyoucanleet.com/>
6 * Available under MIT license <http://mths.be/mit>
8;(function(window, undefined) {
11 /** Used to assign each benchmark an incrimented id */
14 /** Detect DOM document object */
15 var doc = isHostType(window, 'document') && document;
17 /** Detect free variable `define` */
18 var freeDefine = typeof define == 'function' &&
19 typeof define.amd == 'object' && define.amd && define;
21 /** Detect free variable `exports` */
22 var freeExports = typeof exports == 'object' && exports &&
23 (typeof global == 'object' && global && global == global.global && (window = global), exports);
25 /** Detect free variable `require` */
26 var freeRequire = typeof require == 'function' && require;
28 /** Used to crawl all properties regardless of enumerability */
29 var getAllKeys = Object.getOwnPropertyNames;
31 /** Used to get property descriptors */
32 var getDescriptor = Object.getOwnPropertyDescriptor;
34 /** Used in case an object doesn't have its own method */
35 var hasOwnProperty = {}.hasOwnProperty;
37 /** Used to check if an object is extensible */
38 var isExtensible = Object.isExtensible || function() { return true; };
40 /** Used to access Wade Simmons' Node microtime module */
41 var microtimeObject = req('microtime');
43 /** Used to access the browser's high resolution timer */
44 var perfObject = isHostType(window, 'performance') && performance;
46 /** Used to call the browser's high resolution timer */
47 var perfName = perfObject && (
48 perfObject.now && 'now' ||
49 perfObject.webkitNow && 'webkitNow'
52 /** Used to access Node's high resolution timer */
53 var processObject = isHostType(window, 'process') && process;
55 /** Used to check if an own property is enumerable */
56 var propertyIsEnumerable = {}.propertyIsEnumerable;
58 /** Used to set property descriptors */
59 var setDescriptor = Object.defineProperty;
61 /** Used to resolve a value's internal [[Class]] */
62 var toString = {}.toString;
64 /** Used to prevent a `removeChild` memory leak in IE < 9 */
65 var trash = doc && doc.createElement('div');
67 /** Used to integrity check compiled tests */
68 var uid = 'uid' + (+new Date);
70 /** Used to avoid infinite recursion when methods call each other */
73 /** Used to avoid hz of Infinity */
83 * T-Distribution two-tailed critical values for 95% confidence
84 * http://www.itl.nist.gov/div898/handbook/eda/section3/eda3672.htm
87 '1': 12.706,'2': 4.303, '3': 3.182, '4': 2.776, '5': 2.571, '6': 2.447,
88 '7': 2.365, '8': 2.306, '9': 2.262, '10': 2.228, '11': 2.201, '12': 2.179,
89 '13': 2.16, '14': 2.145, '15': 2.131, '16': 2.12, '17': 2.11, '18': 2.101,
90 '19': 2.093, '20': 2.086, '21': 2.08, '22': 2.074, '23': 2.069, '24': 2.064,
91 '25': 2.06, '26': 2.056, '27': 2.052, '28': 2.048, '29': 2.045, '30': 2.042,
96 * Critical Mann-Whitney U-values for 95% confidence
97 * http://www.saburchill.com/IBbiology/stats/003.html
102 '7': [1, 3, 5, 6, 8],
103 '8': [2, 4, 6, 8, 10, 13],
104 '9': [2, 4, 7, 10, 12, 15, 17],
105 '10': [3, 5, 8, 11, 14, 17, 20, 23],
106 '11': [3, 6, 9, 13, 16, 19, 23, 26, 30],
107 '12': [4, 7, 11, 14, 18, 22, 26, 29, 33, 37],
108 '13': [4, 8, 12, 16, 20, 24, 28, 33, 37, 41, 45],
109 '14': [5, 9, 13, 17, 22, 26, 31, 36, 40, 45, 50, 55],
110 '15': [5, 10, 14, 19, 24, 29, 34, 39, 44, 49, 54, 59, 64],
111 '16': [6, 11, 15, 21, 26, 31, 37, 42, 47, 53, 59, 64, 70, 75],
112 '17': [6, 11, 17, 22, 28, 34, 39, 45, 51, 57, 63, 67, 75, 81, 87],
113 '18': [7, 12, 18, 24, 30, 36, 42, 48, 55, 61, 67, 74, 80, 86, 93, 99],
114 '19': [7, 13, 19, 25, 32, 38, 45, 52, 58, 65, 72, 78, 85, 92, 99, 106, 113],
115 '20': [8, 14, 20, 27, 34, 41, 48, 55, 62, 69, 76, 83, 90, 98, 105, 112, 119, 127],
116 '21': [8, 15, 22, 29, 36, 43, 50, 58, 65, 73, 80, 88, 96, 103, 111, 119, 126, 134, 142],
117 '22': [9, 16, 23, 30, 38, 45, 53, 61, 69, 77, 85, 93, 101, 109, 117, 125, 133, 141, 150, 158],
118 '23': [9, 17, 24, 32, 40, 48, 56, 64, 73, 81, 89, 98, 106, 115, 123, 132, 140, 149, 157, 166, 175],
119 '24': [10, 17, 25, 33, 42, 50, 59, 67, 76, 85, 94, 102, 111, 120, 129, 138, 147, 156, 165, 174, 183, 192],
120 '25': [10, 18, 27, 35, 44, 53, 62, 71, 80, 89, 98, 107, 117, 126, 135, 145, 154, 163, 173, 182, 192, 201, 211],
121 '26': [11, 19, 28, 37, 46, 55, 64, 74, 83, 93, 102, 112, 122, 132, 141, 151, 161, 171, 181, 191, 200, 210, 220, 230],
122 '27': [11, 20, 29, 38, 48, 57, 67, 77, 87, 97, 107, 118, 125, 138, 147, 158, 168, 178, 188, 199, 209, 219, 230, 240, 250],
123 '28': [12, 21, 30, 40, 50, 60, 70, 80, 90, 101, 111, 122, 132, 143, 154, 164, 175, 186, 196, 207, 218, 228, 239, 250, 261, 272],
124 '29': [13, 22, 32, 42, 52, 62, 73, 83, 94, 105, 116, 127, 138, 149, 160, 171, 182, 193, 204, 215, 226, 238, 249, 260, 271, 282, 294],
125 '30': [13, 23, 33, 43, 54, 65, 76, 87, 98, 109, 120, 131, 143, 154, 166, 177, 189, 200, 212, 223, 235, 247, 258, 270, 282, 293, 305, 317]
129 * An object used to flag environments/features.
132 * @memberOf Benchmark
142 * @memberOf Benchmark.support
145 support.air = isClassOf(window.runtime, 'ScriptBridgingProxyObject');
148 * Detect if `arguments` objects have the correct internal [[Class]] value.
150 * @memberOf Benchmark.support
153 support.argumentsClass = isClassOf(arguments, 'Arguments');
156 * Detect if in a browser environment.
158 * @memberOf Benchmark.support
161 support.browser = doc && isHostType(window, 'navigator');
164 * Detect if strings support accessing characters by index.
166 * @memberOf Benchmark.support
169 support.charByIndex =
170 // IE 8 supports indexes on string literals but not string objects
171 ('x'[0] + Object('x')[0]) == 'xx';
174 * Detect if strings have indexes as own properties.
176 * @memberOf Benchmark.support
179 support.charByOwnIndex =
180 // Narwhal, Rhino, RingoJS, IE 8, and Opera < 10.52 support indexes on
181 // strings but don't detect them as own properties
182 support.charByIndex && hasKey('x', '0');
185 * Detect if Java is enabled/exposed.
187 * @memberOf Benchmark.support
190 support.java = isClassOf(window.java, 'JavaPackage');
193 * Detect if the Timers API exists.
195 * @memberOf Benchmark.support
198 support.timeout = isHostType(window, 'setTimeout') && isHostType(window, 'clearTimeout');
201 * Detect if functions support decompilation.
203 * @name decompilation
204 * @memberOf Benchmark.support
208 // Safari 2.x removes commas in object literals
209 // from Function#toString results
210 // http://webk.it/11609
211 // Firefox 3.6 and Opera 9.25 strip grouping
212 // parentheses from Function#toString results
213 // http://bugzil.la/559438
214 support.decompilation = Function(
215 'return (' + (function(x) { return { 'x': '' + (1 + x) + '', 'y': 0 }; }) + ')'
218 support.decompilation = false;
222 * Detect ES5+ property descriptor API.
225 * @memberOf Benchmark.support
230 support.descriptors = (setDescriptor(o, o, o), 'value' in getDescriptor(o, o));
232 support.descriptors = false;
236 * Detect ES5+ Object.getOwnPropertyNames().
239 * @memberOf Benchmark.support
243 support.getAllKeys = /\bvalueOf\b/.test(getAllKeys(Object.prototype));
245 support.getAllKeys = false;
249 * Detect if own properties are iterated before inherited properties (all but IE < 9).
251 * @name iteratesOwnLast
252 * @memberOf Benchmark.support
255 support.iteratesOwnFirst = (function() {
257 function ctor() { this.x = 1; }
258 ctor.prototype = { 'y': 1 };
259 for (var prop in new ctor) { props.push(prop); }
260 return props[0] == 'x';
264 * Detect if a node's [[Class]] is resolvable (all but IE < 9)
265 * and that the JS engine errors when attempting to coerce an object to a
266 * string without a `toString` property value of `typeof` "function".
269 * @memberOf Benchmark.support
273 support.nodeClass = ({ 'toString': 0 } + '', toString.call(doc || 0) != '[object Object]');
275 support.nodeClass = true;
280 * Timer object used by `clock()` and `Deferred#resolve`.
288 * The timer namespace object or constructor.
292 * @type Function|Object
297 * Starts the deferred timer.
301 * @param {Object} deferred The deferred instance.
303 'start': null, // lazy defined in `clock()`
306 * Stops the deferred timer.
310 * @param {Object} deferred The deferred instance.
312 'stop': null // lazy defined in `clock()`
315 /** Shortcut for inverse results */
316 var noArgumentsClass = !support.argumentsClass,
317 noCharByIndex = !support.charByIndex,
318 noCharByOwnIndex = !support.charByOwnIndex;
320 /** Math shortcuts */
328 /*--------------------------------------------------------------------------*/
331 * The Benchmark constructor.
334 * @param {String} name A name to identify the benchmark.
335 * @param {Function|String} fn The test to benchmark.
336 * @param {Object} [options={}] Options object.
339 * // basic usage (the `new` operator is optional)
340 * var bench = new Benchmark(fn);
342 * // or using a name first
343 * var bench = new Benchmark('foo', fn);
346 * var bench = new Benchmark('foo', fn, {
348 * // displayed by Benchmark#toString if `name` is not available
351 * // called when the benchmark starts running
352 * 'onStart': onStart,
354 * // called after each run cycle
355 * 'onCycle': onCycle,
357 * // called when aborted
358 * 'onAbort': onAbort,
360 * // called when a test errors
361 * 'onError': onError,
363 * // called when reset
364 * 'onReset': onReset,
366 * // called when the benchmark completes running
367 * 'onComplete': onComplete,
369 * // compiled/called before the test loop
372 * // compiled/called after the test loop
373 * 'teardown': teardown
376 * // or name and options
377 * var bench = new Benchmark('foo', {
379 * // a flag to indicate the benchmark is deferred
382 * // benchmark test function
383 * 'fn': function(deferred) {
384 * // call resolve() when the deferred test is finished
385 * deferred.resolve();
390 * var bench = new Benchmark({
395 * // benchmark test as a string
396 * 'fn': '[1,2,3,4].sort()'
399 * // a test's `this` binding is set to the benchmark instance
400 * var bench = new Benchmark('foo', function() {
401 * 'My name is '.concat(this.name); // My name is foo
404 function Benchmark(name, fn, options) {
407 // allow instance creation without the `new` operator
408 if (me == null || me.constructor != Benchmark) {
409 return new Benchmark(name, fn, options);
412 if (isClassOf(name, 'Object')) {
413 // 1 argument (options)
416 else if (isClassOf(name, 'Function')) {
417 // 2 arguments (fn, options)
421 else if (isClassOf(fn, 'Object')) {
422 // 2 arguments (name, options)
428 // 3 arguments (name, fn [, options])
431 setOptions(me, options);
432 me.id || (me.id = ++counter);
433 me.fn == null && (me.fn = fn);
434 me.stats = deepClone(me.stats);
435 me.times = deepClone(me.times);
439 * The Deferred constructor.
442 * @memberOf Benchmark
443 * @param {Object} clone The cloned benchmark instance.
445 function Deferred(clone) {
447 if (me == null || me.constructor != Deferred) {
448 return new Deferred(clone);
450 me.benchmark = clone;
455 * The Event constructor.
458 * @memberOf Benchmark
459 * @param {String|Object} type The event type.
461 function Event(type) {
463 return (me == null || me.constructor != Event)
465 : (type instanceof Event)
467 : extend(me, { 'timeStamp': +new Date }, typeof type == 'string' ? { 'type': type } : type);
471 * The Suite constructor.
474 * @memberOf Benchmark
475 * @param {String} name A name to identify the suite.
476 * @param {Object} [options={}] Options object.
479 * // basic usage (the `new` operator is optional)
480 * var suite = new Benchmark.Suite;
482 * // or using a name first
483 * var suite = new Benchmark.Suite('foo');
486 * var suite = new Benchmark.Suite('foo', {
488 * // called when the suite starts running
489 * 'onStart': onStart,
491 * // called between running benchmarks
492 * 'onCycle': onCycle,
494 * // called when aborted
495 * 'onAbort': onAbort,
497 * // called when a test errors
498 * 'onError': onError,
500 * // called when reset
501 * 'onReset': onReset,
503 * // called when the suite completes running
504 * 'onComplete': onComplete
507 function Suite(name, options) {
510 // allow instance creation without the `new` operator
511 if (me == null || me.constructor != Suite) {
512 return new Suite(name, options);
515 if (isClassOf(name, 'Object')) {
516 // 1 argument (options)
519 // 2 arguments (name [, options])
522 setOptions(me, options);
525 /*--------------------------------------------------------------------------*/
528 * Note: Some array methods have been implemented in plain JavaScript to avoid
529 * bugs in IE, Opera, Rhino, and Mobile Safari.
531 * IE compatibility mode and IE < 9 have buggy Array `shift()` and `splice()`
532 * functions that fail to remove the last element, `object[0]`, of
533 * array-like-objects even though the `length` property is set to `0`.
534 * The `shift()` method is buggy in IE 8 compatibility mode, while `splice()`
535 * is buggy regardless of mode in IE < 9 and buggy in compatibility mode in IE 9.
537 * In Opera < 9.50 and some older/beta Mobile Safari versions using `unshift()`
538 * generically to augment the `arguments` object will pave the value at index 0
539 * without incrimenting the other values's indexes.
540 * https://github.com/documentcloud/underscore/issues/9
542 * Rhino and environments it powers, like Narwhal and RingoJS, may have
543 * buggy Array `concat()`, `reverse()`, `shift()`, `slice()`, `splice()` and
544 * `unshift()` functions that make sparse arrays non-sparse by assigning the
545 * undefined indexes a value of undefined.
546 * https://github.com/mozilla/rhino/commit/702abfed3f8ca043b2636efd31c14ba7552603dd
550 * Creates an array containing the elements of the host array followed by the
551 * elements of each argument in order.
553 * @memberOf Benchmark.Suite
554 * @returns {Array} The new array.
559 length = arguments.length,
560 result = slice.call(this),
561 index = result.length;
563 while (++j < length) {
564 value = arguments[j];
565 if (isClassOf(value, 'Array')) {
566 for (var k = 0, l = value.length; k < l; k++, index++) {
568 result[index] = value[k];
572 result[index++] = value;
579 * Utility function used by `shift()`, `splice()`, and `unshift()`.
582 * @param {Number} start The index to start inserting elements.
583 * @param {Number} deleteCount The number of elements to delete from the insert point.
584 * @param {Array} elements The elements to insert.
585 * @returns {Array} An array of deleted elements.
587 function insert(start, deleteCount, elements) {
588 // `result` should have its length set to the `deleteCount`
589 // see https://bugs.ecmascript.org/show_bug.cgi?id=332
590 var deleteEnd = start + deleteCount,
591 elementCount = elements ? elements.length : 0,
593 length = start + elementCount,
595 result = Array(deleteCount),
596 tail = slice.call(object, deleteEnd);
598 // delete elements from the array
599 while (++index < deleteEnd) {
600 if (index in object) {
601 result[index - start] = object[index];
602 delete object[index];
607 while (++index < length) {
608 object[index] = elements[index - start];
610 // append tail elements
612 length = max(0, (object.length >>> 0) - deleteCount + elementCount);
613 while (++index < length) {
614 if ((index - start) in tail) {
615 object[index] = tail[index - start];
616 } else if (index in object) {
617 delete object[index];
620 // delete excess elements
621 deleteCount = deleteCount > elementCount ? deleteCount - elementCount : 0;
622 while (deleteCount--) {
623 index = length + deleteCount;
624 if (index in object) {
625 delete object[index];
628 object.length = length;
633 * Rearrange the host array's elements in reverse order.
635 * @memberOf Benchmark.Suite
636 * @returns {Array} The reversed array.
642 object = Object(this),
643 length = object.length >>> 0,
644 middle = floor(length / 2);
647 while (++index < middle) {
648 upperIndex = length - index - 1;
649 value = upperIndex in object ? object[upperIndex] : uid;
650 if (index in object) {
651 object[upperIndex] = object[index];
653 delete object[upperIndex];
656 object[index] = value;
658 delete object[index];
666 * Removes the first element of the host array and returns it.
668 * @memberOf Benchmark.Suite
669 * @returns {Mixed} The first element of the array.
672 return insert.call(this, 0, 1)[0];
676 * Creates an array of the host array's elements from the start index up to,
677 * but not including, the end index.
679 * @memberOf Benchmark.Suite
680 * @param {Number} start The starting index.
681 * @param {Number} end The end index.
682 * @returns {Array} The new array.
684 function slice(start, end) {
686 object = Object(this),
687 length = object.length >>> 0,
690 start = toInteger(start);
691 start = start < 0 ? max(length + start, 0) : min(start, length);
693 end = end == null ? length : toInteger(end);
694 end = end < 0 ? max(length + end, 0) : min(end, length);
696 while ((++index, ++start) < end) {
697 if (start in object) {
698 result[index] = object[start];
705 * Allows removing a range of elements and/or inserting elements into the
708 * @memberOf Benchmark.Suite
709 * @param {Number} start The start index.
710 * @param {Number} deleteCount The number of elements to delete.
711 * @param {Mixed} [val1, val2, ...] values to insert at the `start` index.
712 * @returns {Array} An array of removed elements.
714 function splice(start, deleteCount) {
715 var object = Object(this),
716 length = object.length >>> 0;
718 start = toInteger(start);
719 start = start < 0 ? max(length + start, 0) : min(start, length);
721 // support the de-facto SpiderMonkey extension
722 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice#Parameters
723 // https://bugs.ecmascript.org/show_bug.cgi?id=429
724 deleteCount = arguments.length == 1
726 : min(max(toInteger(deleteCount), 0), length - start);
728 return insert.call(object, start, deleteCount, slice.call(arguments, 2));
732 * Converts the specified `value` to an integer.
735 * @param {Mixed} value The value to convert.
736 * @returns {Number} The resulting integer.
738 function toInteger(value) {
740 return value === 0 || !isFinite(value) ? value || 0 : value - (value % 1);
744 * Appends arguments to the host array.
746 * @memberOf Benchmark.Suite
747 * @returns {Number} The new length.
750 var object = Object(this);
751 insert.call(object, 0, 0, arguments);
752 return object.length;
755 /*--------------------------------------------------------------------------*/
758 * A generic `Function#bind` like method.
761 * @param {Function} fn The function to be bound to `thisArg`.
762 * @param {Mixed} thisArg The `this` binding for the given function.
763 * @returns {Function} The bound function.
765 function bind(fn, thisArg) {
766 return function() { fn.apply(thisArg, arguments); };
770 * Creates a function from the given arguments string and body.
773 * @param {String} args The comma separated function arguments.
774 * @param {String} body The function body.
775 * @returns {Function} The new function.
777 function createFunction() {
779 createFunction = function(args, body) {
781 anchor = freeDefine ? define.amd : Benchmark,
782 prop = uid + 'createFunction';
784 runScript((freeDefine ? 'define.amd.' : 'Benchmark.') + prop + '=function(' + args + '){' + body + '}');
785 result = anchor[prop];
789 // fix JaegerMonkey bug
790 // http://bugzil.la/639720
791 createFunction = support.browser && (createFunction('', 'return"' + uid + '"') || noop)() == uid ? createFunction : Function;
792 return createFunction.apply(null, arguments);
796 * Delay the execution of a function based on the benchmark's `delay` property.
799 * @param {Object} bench The benchmark instance.
800 * @param {Object} fn The function to execute.
802 function delay(bench, fn) {
803 bench._timerId = setTimeout(fn, bench.delay * 1e3);
807 * Destroys the given element.
810 * @param {Element} element The element to destroy.
812 function destroyElement(element) {
813 trash.appendChild(element);
814 trash.innerHTML = '';
818 * Iterates over an object's properties, executing the `callback` for each.
819 * Callbacks may terminate the loop by explicitly returning `false`.
822 * @param {Object} object The object to iterate over.
823 * @param {Function} callback The function executed per own property.
824 * @param {Object} options The options object.
825 * @returns {Object} Returns the object iterated over.
827 function forProps() {
831 shadowed = ['constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf'];
833 (function(enumFlag, key) {
834 // must use a non-native constructor to catch the Safari 2 issue
835 function Klass() { this.valueOf = 0; };
836 Klass.prototype.valueOf = 0;
837 // check various for-in bugs
838 for (key in new Klass) {
839 enumFlag += key == 'valueOf' ? 1 : 0;
841 // check if `arguments` objects have non-enumerable indexes
842 for (key in arguments) {
843 key == '0' && (forArgs = false);
845 // Safari 2 iterates over shadowed properties twice
846 // http://replay.waybackmachine.org/20090428222941/http://tobielangel.com/2007/1/29/for-in-loop-broken-in-safari/
847 skipSeen = enumFlag == 2;
848 // IE < 9 incorrectly makes an object's properties non-enumerable if they have
849 // the same name as other non-enumerable properties in its prototype chain.
850 forShadowed = !enumFlag;
854 forProps = function(object, callback, options) {
855 options || (options = {});
858 object = Object(object);
865 which = options.which,
866 allFlag = which == 'all',
869 length = object.length,
870 ownFlag = allFlag || which == 'own',
872 skipProto = isClassOf(object, 'Function'),
873 thisArg = options.bind;
875 if (thisArg !== undefined) {
876 callback = bind(callback, thisArg);
878 // iterate all properties
879 if (allFlag && support.getAllKeys) {
880 for (index = 0, keys = getAllKeys(object), length = keys.length; index < length; index++) {
882 if (callback(object[key], key, object) === false) {
887 // else iterate only enumerable properties
889 for (key in object) {
890 // Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1
891 // (if the prototype or a property on the prototype has been set)
892 // incorrectly set a function's `prototype` property [[Enumerable]] value
893 // to `true`. Because of this we standardize on skipping the `prototype`
894 // property of functions regardless of their [[Enumerable]] value.
896 !(skipProto && key == 'prototype') &&
897 !(skipSeen && (hasKey(seen, key) || !(seen[key] = true))) &&
898 (!ownFlag || ownFlag && hasKey(object, key)) &&
899 callback(object[key], key, object) === false)) {
903 // in IE < 9 strings don't support accessing characters by index
904 if (!done && (forArgs && isArguments(object) ||
905 ((noCharByIndex || noCharByOwnIndex) && isClassOf(object, 'String') &&
906 (iteratee = noCharByIndex ? object.split('') : object)))) {
907 while (++index < length) {
909 callback(iteratee[index], String(index), object) === false)) {
914 if (!done && forShadowed) {
915 // Because IE < 9 can't set the `[[Enumerable]]` attribute of an existing
916 // property and the `constructor` property of a prototype defaults to
917 // non-enumerable, we manually skip the `constructor` property when we
918 // think we are iterating over a `prototype` object.
919 ctor = object.constructor;
920 skipCtor = ctor && ctor.prototype && ctor.prototype.constructor === ctor;
921 for (index = 0; index < 7; index++) {
922 key = shadowed[index];
923 if (!(skipCtor && key == 'constructor') &&
924 hasKey(object, key) &&
925 callback(object[key], key, object) === false) {
933 return forProps.apply(null, arguments);
937 * Gets the name of the first argument from a function's source.
940 * @param {Function} fn The function.
941 * @returns {String} The argument name.
943 function getFirstArgument(fn) {
944 return (!hasKey(fn, 'toString') &&
945 (/^[\s(]*function[^(]*\(([^\s,)]+)/.exec(fn) || 0)[1]) || '';
949 * Computes the arithmetic mean of a sample.
952 * @param {Array} sample The sample.
953 * @returns {Number} The mean.
955 function getMean(sample) {
956 return reduce(sample, function(sum, x) {
958 }) / sample.length || 0;
962 * Gets the source code of a function.
965 * @param {Function} fn The function.
966 * @param {String} altSource A string used when a function's source code is unretrievable.
967 * @returns {String} The function's source code.
969 function getSource(fn, altSource) {
970 var result = altSource;
971 if (isStringable(fn)) {
973 } else if (support.decompilation) {
974 // escape the `{` for Firefox 1
975 result = (/^[^{]+\{([\s\S]*)}\s*$/.exec(fn) || 0)[1];
978 result = (result || '').replace(/^\s+|\s+$/g, '');
980 // detect strings containing only the "use strict" directive
981 return /^(?:\/\*+[\w|\W]*?\*\/|\/\/.*?[\n\r\u2028\u2029]|\s)*(["'])use strict\1;?$/.test(result)
987 * Checks if a value is an `arguments` object.
990 * @param {Mixed} value The value to check.
991 * @returns {Boolean} Returns `true` if the value is an `arguments` object, else `false`.
993 function isArguments() {
995 isArguments = function(value) {
996 return toString.call(value) == '[object Arguments]';
998 if (noArgumentsClass) {
999 isArguments = function(value) {
1000 return hasKey(value, 'callee') &&
1001 !(propertyIsEnumerable && propertyIsEnumerable.call(value, 'callee'));
1004 return isArguments(arguments[0]);
1008 * Checks if an object is of the specified class.
1011 * @param {Mixed} value The value to check.
1012 * @param {String} name The name of the class.
1013 * @returns {Boolean} Returns `true` if the value is of the specified class, else `false`.
1015 function isClassOf(value, name) {
1016 return value != null && toString.call(value) == '[object ' + name + ']';
1020 * Host objects can return type values that are different from their actual
1021 * data type. The objects we are concerned with usually return non-primitive
1022 * types of object, function, or unknown.
1025 * @param {Mixed} object The owner of the property.
1026 * @param {String} property The property to check.
1027 * @returns {Boolean} Returns `true` if the property value is a non-primitive, else `false`.
1029 function isHostType(object, property) {
1030 var type = object != null ? typeof object[property] : 'number';
1031 return !/^(?:boolean|number|string|undefined)$/.test(type) &&
1032 (type == 'object' ? !!object[property] : true);
1036 * Checks if a given `value` is an object created by the `Object` constructor
1037 * assuming objects created by the `Object` constructor have no inherited
1038 * enumerable properties and that there are no `Object.prototype` extensions.
1041 * @param {Mixed} value The value to check.
1042 * @returns {Boolean} Returns `true` if the `value` is a plain `Object` object, else `false`.
1044 function isPlainObject(value) {
1045 // avoid non-objects and false positives for `arguments` objects in IE < 9
1047 if (!(value && typeof value == 'object') || isArguments(value)) {
1050 // IE < 9 presents DOM nodes as `Object` objects except they have `toString`
1051 // methods that are `typeof` "string" and still can coerce nodes to strings.
1052 // Also check that the constructor is `Object` (i.e. `Object instanceof Object`)
1053 var ctor = value.constructor;
1054 if ((support.nodeClass || !(typeof value.toString != 'function' && typeof (value + '') == 'string')) &&
1055 (!isClassOf(ctor, 'Function') || ctor instanceof ctor)) {
1056 // In most environments an object's own properties are iterated before
1057 // its inherited properties. If the last iterated property is an object's
1058 // own property then there are no inherited enumerable properties.
1059 if (support.iteratesOwnFirst) {
1060 forProps(value, function(subValue, subKey) {
1063 return result === false || hasKey(value, result);
1065 // IE < 9 iterates inherited properties before own properties. If the first
1066 // iterated property is an object's own property then there are no inherited
1067 // enumerable properties.
1068 forProps(value, function(subValue, subKey) {
1069 result = !hasKey(value, subKey);
1072 return result === false;
1078 * Checks if a value can be safely coerced to a string.
1081 * @param {Mixed} value The value to check.
1082 * @returns {Boolean} Returns `true` if the value can be coerced, else `false`.
1084 function isStringable(value) {
1085 return hasKey(value, 'toString') || isClassOf(value, 'String');
1089 * Wraps a function and passes `this` to the original function as the
1093 * @param {Function} fn The function to be wrapped.
1094 * @returns {Function} The new function.
1096 function methodize(fn) {
1099 args.push.apply(args, arguments);
1100 return fn.apply(null, args);
1105 * A no-operation function.
1110 // no operation performed
1114 * A wrapper around require() to suppress `module missing` errors.
1117 * @param {String} id The module id.
1118 * @returns {Mixed} The exported module or `null`.
1122 var result = freeExports && freeRequire(id);
1124 return result || null;
1128 * Runs a snippet of JavaScript via script injection.
1131 * @param {String} code The code to run.
1133 function runScript(code) {
1134 var anchor = freeDefine ? define.amd : Benchmark,
1135 script = doc.createElement('script'),
1136 sibling = doc.getElementsByTagName('script')[0],
1137 parent = sibling.parentNode,
1138 prop = uid + 'runScript',
1139 prefix = '(' + (freeDefine ? 'define.amd.' : 'Benchmark.') + prop + '||function(){})();';
1141 // Firefox 2.0.0.2 cannot use script injection as intended because it executes
1142 // asynchronously, but that's OK because script injection is only used to avoid
1143 // the previously commented JaegerMonkey bug.
1145 // remove the inserted script *before* running the code to avoid differences
1146 // in the expected script element count/order of the document.
1147 script.appendChild(doc.createTextNode(prefix + code));
1148 anchor[prop] = function() { destroyElement(script); };
1150 parent = parent.cloneNode(false);
1154 parent.insertBefore(script, sibling);
1155 delete anchor[prop];
1159 * A helper function for setting options/event handlers.
1162 * @param {Object} bench The benchmark instance.
1163 * @param {Object} [options={}] Options object.
1165 function setOptions(bench, options) {
1166 options = extend({}, bench.constructor.options, options);
1167 bench.options = forOwn(options, function(value, key) {
1168 if (value != null) {
1169 // add event listeners
1170 if (/^on[A-Z]/.test(key)) {
1171 forEach(key.split(' '), function(key) {
1172 bench.on(key.slice(2).toLowerCase(), value);
1174 } else if (!hasKey(bench, key)) {
1175 bench[key] = deepClone(value);
1181 /*--------------------------------------------------------------------------*/
1184 * Handles cycling/completing the deferred benchmark.
1186 * @memberOf Benchmark.Deferred
1188 function resolve() {
1190 clone = me.benchmark,
1191 bench = clone._original;
1193 if (bench.aborted) {
1194 // cycle() -> clone cycle/complete event -> compute()'s invoked bench.run() cycle/complete
1196 clone.running = false;
1199 else if (++me.cycles < clone.count) {
1200 // continue the test loop
1201 if (support.timeout) {
1202 // use setTimeout to avoid a call stack overflow if called recursively
1203 setTimeout(function() { clone.compiled.call(me, timer); }, 0);
1205 clone.compiled.call(me, timer);
1211 delay(clone, function() { cycle(me); });
1215 /*--------------------------------------------------------------------------*/
1218 * A deep clone utility.
1221 * @memberOf Benchmark
1222 * @param {Mixed} value The value to clone.
1223 * @returns {Mixed} The cloned value.
1225 function deepClone(value) {
1239 data = { 'value': value },
1242 queue = { 'length': 0 },
1246 * An easily detectable decorator for cloned values.
1248 function Marker(object) {
1253 * The callback used by `forProps()`.
1255 function forPropsCallback(subValue, subKey) {
1256 // exit early to avoid cloning the marker
1257 if (subValue && subValue.constructor == Marker) {
1260 // add objects to the queue
1261 if (subValue === Object(subValue)) {
1262 queue[queue.length++] = { 'key': subKey, 'parent': clone, 'source': value };
1264 // assign non-objects
1267 // will throw an error in strict mode if the property is read-only
1268 clone[subKey] = subValue;
1274 * Gets an available marker key for the given object.
1276 function getMarkerKey(object) {
1277 // avoid collisions with existing keys
1279 while (object[result] && object[result].constructor != Marker) {
1287 parent = data.parent;
1288 source = data.source;
1289 clone = value = source ? source[key] : data.value;
1290 accessor = circular = descriptor = false;
1292 // create a basic clone to filter out functions, DOM elements, and
1293 // other non `Object` objects
1294 if (value === Object(value)) {
1295 // use custom deep clone function if available
1296 if (isClassOf(value.deepClone, 'Function')) {
1297 clone = value.deepClone();
1299 ctor = value.constructor;
1300 switch (toString.call(value)) {
1301 case '[object Array]':
1302 clone = new ctor(value.length);
1305 case '[object Boolean]':
1306 clone = new ctor(value == true);
1309 case '[object Date]':
1310 clone = new ctor(+value);
1313 case '[object Object]':
1314 isPlainObject(value) && (clone = {});
1317 case '[object Number]':
1318 case '[object String]':
1319 clone = new ctor(value);
1322 case '[object RegExp]':
1323 clone = ctor(value.source,
1324 (value.global ? 'g' : '') +
1325 (value.ignoreCase ? 'i' : '') +
1326 (value.multiline ? 'm' : ''));
1329 // continue clone if `value` doesn't have an accessor descriptor
1330 // http://es5.github.com/#x8.10.1
1331 if (clone && clone != value &&
1332 !(descriptor = source && support.descriptors && getDescriptor(source, key),
1333 accessor = descriptor && (descriptor.get || descriptor.set))) {
1334 // use an existing clone (circular reference)
1335 if ((extensible = isExtensible(value))) {
1336 markerKey = getMarkerKey(value);
1337 if (value[markerKey]) {
1338 circular = clone = value[markerKey].raw;
1341 // for frozen/sealed objects
1342 for (subIndex = 0, length = unmarked.length; subIndex < length; subIndex++) {
1343 data = unmarked[subIndex];
1344 if (data.object === value) {
1345 circular = clone = data.clone;
1351 // mark object to allow quickly detecting circular references and tie it to its clone
1353 value[markerKey] = new Marker(clone);
1354 marked.push({ 'key': markerKey, 'object': value });
1356 // for frozen/sealed objects
1357 unmarked.push({ 'clone': clone, 'object': value });
1359 // iterate over object properties
1360 forProps(value, forPropsCallback, { 'which': 'all' });
1365 // for custom property descriptors
1366 if (accessor || (descriptor && !(descriptor.configurable && descriptor.enumerable && descriptor.writable))) {
1367 if ('value' in descriptor) {
1368 descriptor.value = clone;
1370 setDescriptor(parent, key, descriptor);
1372 // for default property descriptors
1374 parent[key] = clone;
1379 } while ((data = queue[index++]));
1382 for (index = 0, length = marked.length; index < length; index++) {
1383 data = marked[index];
1384 delete data.object[data.key];
1390 * An iteration utility for arrays and objects.
1391 * Callbacks may terminate the loop by explicitly returning `false`.
1394 * @memberOf Benchmark
1395 * @param {Array|Object} object The object to iterate over.
1396 * @param {Function} callback The function called per iteration.
1397 * @param {Mixed} thisArg The `this` binding for the callback.
1398 * @returns {Array|Object} Returns the object iterated over.
1400 function each(object, callback, thisArg) {
1401 var result = object;
1402 object = Object(object);
1406 length = object.length,
1407 isSnapshot = !!(object.snapshotItem && (length = object.snapshotLength)),
1408 isSplittable = (noCharByIndex || noCharByOwnIndex) && isClassOf(object, 'String'),
1409 isConvertable = isSnapshot || isSplittable || 'item' in object,
1410 origObject = object;
1412 // in Opera < 10.5 `hasKey(object, 'length')` returns `false` for NodeLists
1413 if (length === length >>> 0) {
1414 if (isConvertable) {
1415 // the third argument of the callback is the original non-array object
1416 callback = function(value, index) {
1417 return fn.call(this, value, index, origObject);
1419 // in IE < 9 strings don't support accessing characters by index
1421 object = object.split('');
1424 while (++index < length) {
1425 // in Safari 2 `index in object` is always `false` for NodeLists
1426 object[index] = isSnapshot ? result.snapshotItem(index) : result[index];
1430 forEach(object, callback, thisArg);
1432 forOwn(object, callback, thisArg);
1438 * Copies enumerable properties from the source(s) object to the destination object.
1441 * @memberOf Benchmark
1442 * @param {Object} destination The destination object.
1443 * @param {Object} [source={}] The source object.
1444 * @returns {Object} The destination object.
1446 function extend(destination, source) {
1447 // Chrome < 14 incorrectly sets `destination` to `undefined` when we `delete arguments[0]`
1448 // http://code.google.com/p/v8/issues/detail?id=839
1449 var result = destination;
1450 delete arguments[0];
1452 forEach(arguments, function(source) {
1453 forProps(source, function(value, key) {
1454 result[key] = value;
1461 * A generic `Array#filter` like method.
1464 * @memberOf Benchmark
1465 * @param {Array} array The array to iterate over.
1466 * @param {Function|String} callback The function/alias called per iteration.
1467 * @param {Mixed} thisArg The `this` binding for the callback.
1468 * @returns {Array} A new array of values that passed callback filter.
1471 * // get odd numbers
1472 * Benchmark.filter([1, 2, 3, 4, 5], function(n) {
1474 * }); // -> [1, 3, 5];
1476 * // get fastest benchmarks
1477 * Benchmark.filter(benches, 'fastest');
1479 * // get slowest benchmarks
1480 * Benchmark.filter(benches, 'slowest');
1482 * // get benchmarks that completed without erroring
1483 * Benchmark.filter(benches, 'successful');
1485 function filter(array, callback, thisArg) {
1488 if (callback == 'successful') {
1489 // callback to exclude those that are errored, unrun, or have hz of Infinity
1490 callback = function(bench) { return bench.cycles && isFinite(bench.hz); };
1492 else if (callback == 'fastest' || callback == 'slowest') {
1493 // get successful, sort by period + margin of error, and filter fastest/slowest
1494 result = filter(array, 'successful').sort(function(a, b) {
1495 a = a.stats; b = b.stats;
1496 return (a.mean + a.moe > b.mean + b.moe ? 1 : -1) * (callback == 'fastest' ? 1 : -1);
1498 result = filter(result, function(bench) {
1499 return result[0].compare(bench) == 0;
1502 return result || reduce(array, function(result, value, index) {
1503 return callback.call(thisArg, value, index, array) ? (result.push(value), result) : result;
1508 * A generic `Array#forEach` like method.
1509 * Callbacks may terminate the loop by explicitly returning `false`.
1512 * @memberOf Benchmark
1513 * @param {Array} array The array to iterate over.
1514 * @param {Function} callback The function called per iteration.
1515 * @param {Mixed} thisArg The `this` binding for the callback.
1516 * @returns {Array} Returns the array iterated over.
1518 function forEach(array, callback, thisArg) {
1520 length = (array = Object(array)).length >>> 0;
1522 if (thisArg !== undefined) {
1523 callback = bind(callback, thisArg);
1525 while (++index < length) {
1526 if (index in array &&
1527 callback(array[index], index, array) === false) {
1535 * Iterates over an object's own properties, executing the `callback` for each.
1536 * Callbacks may terminate the loop by explicitly returning `false`.
1539 * @memberOf Benchmark
1540 * @param {Object} object The object to iterate over.
1541 * @param {Function} callback The function executed per own property.
1542 * @param {Mixed} thisArg The `this` binding for the callback.
1543 * @returns {Object} Returns the object iterated over.
1545 function forOwn(object, callback, thisArg) {
1546 return forProps(object, callback, { 'bind': thisArg, 'which': 'own' });
1550 * Converts a number to a more readable comma-separated string representation.
1553 * @memberOf Benchmark
1554 * @param {Number} number The number to convert.
1555 * @returns {String} The more readable string representation.
1557 function formatNumber(number) {
1558 number = String(number).split('.');
1559 return number[0].replace(/(?=(?:\d{3})+$)(?!\b)/g, ',') +
1560 (number[1] ? '.' + number[1] : '');
1564 * Checks if an object has the specified key as a direct property.
1567 * @memberOf Benchmark
1568 * @param {Object} object The object to check.
1569 * @param {String} key The key to check for.
1570 * @returns {Boolean} Returns `true` if key is a direct property, else `false`.
1573 // lazy define for worst case fallback (not as accurate)
1574 hasKey = function(object, key) {
1575 var parent = object != null && (object.constructor || Object).prototype;
1576 return !!parent && key in Object(object) && !(key in parent && object[key] === parent[key]);
1578 // for modern browsers
1579 if (isClassOf(hasOwnProperty, 'Function')) {
1580 hasKey = function(object, key) {
1581 return object != null && hasOwnProperty.call(object, key);
1585 else if ({}.__proto__ == Object.prototype) {
1586 hasKey = function(object, key) {
1588 if (object != null) {
1589 object = Object(object);
1590 object.__proto__ = [object.__proto__, object.__proto__ = null, result = key in object][0];
1595 return hasKey.apply(this, arguments);
1599 * A generic `Array#indexOf` like method.
1602 * @memberOf Benchmark
1603 * @param {Array} array The array to iterate over.
1604 * @param {Mixed} value The value to search for.
1605 * @param {Number} [fromIndex=0] The index to start searching from.
1606 * @returns {Number} The index of the matched value or `-1`.
1608 function indexOf(array, value, fromIndex) {
1609 var index = toInteger(fromIndex),
1610 length = (array = Object(array)).length >>> 0;
1612 index = (index < 0 ? max(0, length + index) : index) - 1;
1613 while (++index < length) {
1614 if (index in array && value === array[index]) {
1622 * Modify a string by replacing named tokens with matching object property values.
1625 * @memberOf Benchmark
1626 * @param {String} string The string to modify.
1627 * @param {Object} object The template object.
1628 * @returns {String} The modified string.
1630 function interpolate(string, object) {
1631 forOwn(object, function(value, key) {
1632 // escape regexp special characters in `key`
1633 string = string.replace(RegExp('#\\{' + key.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1') + '\\}', 'g'), value);
1639 * Invokes a method on all items in an array.
1642 * @memberOf Benchmark
1643 * @param {Array} benches Array of benchmarks to iterate over.
1644 * @param {String|Object} name The name of the method to invoke OR options object.
1645 * @param {Mixed} [arg1, arg2, ...] Arguments to invoke the method with.
1646 * @returns {Array} A new array of values returned from each method invoked.
1649 * // invoke `reset` on all benchmarks
1650 * Benchmark.invoke(benches, 'reset');
1652 * // invoke `emit` with arguments
1653 * Benchmark.invoke(benches, 'emit', 'complete', listener);
1655 * // invoke `run(true)`, treat benchmarks as a queue, and register invoke callbacks
1656 * Benchmark.invoke(benches, {
1658 * // invoke the `run` method
1661 * // pass a single argument
1664 * // treat as queue, removing benchmarks from front of `benches` until empty
1667 * // called before any benchmarks have been invoked.
1668 * 'onStart': onStart,
1670 * // called between invoking benchmarks
1671 * 'onCycle': onCycle,
1673 * // called after all benchmarks have been invoked.
1674 * 'onComplete': onComplete
1677 function invoke(benches, name) {
1682 eventProps = { 'currentTarget': benches },
1683 options = { 'onStart': noop, 'onCycle': noop, 'onComplete': noop },
1684 result = map(benches, function(bench) { return bench; });
1687 * Invokes the method of the current object and if synchronous, fetches the next.
1689 function execute() {
1691 async = isAsync(bench);
1694 // use `getNext` as the first listener
1695 bench.on('complete', getNext);
1696 listeners = bench.events.complete;
1697 listeners.splice(0, 0, listeners.pop());
1700 result[index] = isClassOf(bench && bench[name], 'Function') ? bench[name].apply(bench, args) : undefined;
1701 // if synchronous return true until finished
1702 return !async && getNext();
1706 * Fetches the next bench or executes `onComplete` callback.
1708 function getNext(event) {
1711 async = isAsync(last);
1714 last.off('complete', getNext);
1715 last.emit('complete');
1717 // emit "cycle" event
1718 eventProps.type = 'cycle';
1719 eventProps.target = last;
1720 cycleEvent = Event(eventProps);
1721 options.onCycle.call(benches, cycleEvent);
1723 // choose next benchmark if not exiting early
1724 if (!cycleEvent.aborted && raiseIndex() !== false) {
1725 bench = queued ? benches[0] : result[index];
1726 if (isAsync(bench)) {
1727 delay(bench, execute);
1730 // resume execution if previously asynchronous but now synchronous
1731 while (execute()) { }
1734 // continue synchronous execution
1738 // emit "complete" event
1739 eventProps.type = 'complete';
1740 options.onComplete.call(benches, Event(eventProps));
1742 // When used as a listener `event.aborted = true` will cancel the rest of
1743 // the "complete" listeners because they were already called above and when
1744 // used as part of `getNext` the `return false` will exit the execution while-loop.
1746 event.aborted = true;
1753 * Checks if invoking `Benchmark#run` with asynchronous cycles.
1755 function isAsync(object) {
1756 // avoid using `instanceof` here because of IE memory leak issues with host objects
1757 var async = args[0] && args[0].async;
1758 return Object(object).constructor == Benchmark && name == 'run' &&
1759 ((async == null ? object.options.async : async) && support.timeout || object.defer);
1763 * Raises `index` to the next defined index or returns `false`.
1765 function raiseIndex() {
1766 var length = result.length;
1768 // if queued remove the previous bench and subsequent skipped non-entries
1770 ++index > 0 && shift.call(benches);
1771 } while ((length = benches.length) && !('0' in benches));
1774 while (++index < length && !(index in result)) { }
1776 // if we reached the last index then return `false`
1777 return (queued ? length : index < length) ? index : (index = false);
1781 if (isClassOf(name, 'String')) {
1782 // 2 arguments (array, name)
1783 args = slice.call(arguments, 2);
1785 // 2 arguments (array, options)
1786 options = extend(options, name);
1787 name = options.name;
1788 args = isClassOf(args = 'args' in options ? options.args : [], 'Array') ? args : [args];
1789 queued = options.queued;
1792 // start iterating over the array
1793 if (raiseIndex() !== false) {
1794 // emit "start" event
1795 bench = result[index];
1796 eventProps.type = 'start';
1797 eventProps.target = bench;
1798 options.onStart.call(benches, Event(eventProps));
1800 // end early if the suite was aborted in an "onStart" listener
1801 if (benches.aborted && benches.constructor == Suite && name == 'run') {
1802 // emit "cycle" event
1803 eventProps.type = 'cycle';
1804 options.onCycle.call(benches, Event(eventProps));
1805 // emit "complete" event
1806 eventProps.type = 'complete';
1807 options.onComplete.call(benches, Event(eventProps));
1811 if (isAsync(bench)) {
1812 delay(bench, execute);
1814 while (execute()) { }
1822 * Creates a string of joined array values or object key-value pairs.
1825 * @memberOf Benchmark
1826 * @param {Array|Object} object The object to operate on.
1827 * @param {String} [separator1=','] The separator used between key-value pairs.
1828 * @param {String} [separator2=': '] The separator used between keys and values.
1829 * @returns {String} The joined result.
1831 function join(object, separator1, separator2) {
1833 length = (object = Object(object)).length,
1834 arrayLike = length === length >>> 0;
1836 separator2 || (separator2 = ': ');
1837 each(object, function(value, key) {
1838 result.push(arrayLike ? value : key + separator2 + value);
1840 return result.join(separator1 || ',');
1844 * A generic `Array#map` like method.
1847 * @memberOf Benchmark
1848 * @param {Array} array The array to iterate over.
1849 * @param {Function} callback The function called per iteration.
1850 * @param {Mixed} thisArg The `this` binding for the callback.
1851 * @returns {Array} A new array of values returned by the callback.
1853 function map(array, callback, thisArg) {
1854 return reduce(array, function(result, value, index) {
1855 result[index] = callback.call(thisArg, value, index, array);
1857 }, Array(Object(array).length >>> 0));
1861 * Retrieves the value of a specified property from all items in an array.
1864 * @memberOf Benchmark
1865 * @param {Array} array The array to iterate over.
1866 * @param {String} property The property to pluck.
1867 * @returns {Array} A new array of property values.
1869 function pluck(array, property) {
1870 return map(array, function(object) {
1871 return object == null ? undefined : object[property];
1876 * A generic `Array#reduce` like method.
1879 * @memberOf Benchmark
1880 * @param {Array} array The array to iterate over.
1881 * @param {Function} callback The function called per iteration.
1882 * @param {Mixed} accumulator Initial value of the accumulator.
1883 * @returns {Mixed} The accumulator.
1885 function reduce(array, callback, accumulator) {
1886 var noaccum = arguments.length < 3;
1887 forEach(array, function(value, index) {
1888 accumulator = noaccum ? (noaccum = false, value) : callback(accumulator, value, index, array);
1893 /*--------------------------------------------------------------------------*/
1896 * Aborts all benchmarks in the suite.
1899 * @memberOf Benchmark.Suite
1900 * @returns {Object} The suite instance.
1902 function abortSuite() {
1905 resetting = calledBy.resetSuite;
1908 event = Event('abort');
1910 if (!event.cancelled || resetting) {
1911 // avoid infinite recursion
1912 calledBy.abortSuite = true;
1914 delete calledBy.abortSuite;
1918 invoke(me, 'abort');
1926 * Adds a test to the benchmark suite.
1928 * @memberOf Benchmark.Suite
1929 * @param {String} name A name to identify the benchmark.
1930 * @param {Function|String} fn The test to benchmark.
1931 * @param {Object} [options={}] Options object.
1932 * @returns {Object} The benchmark instance.
1938 * // or using a name first
1939 * suite.add('foo', fn);
1941 * // or with options
1942 * suite.add('foo', fn, {
1943 * 'onCycle': onCycle,
1944 * 'onComplete': onComplete
1947 * // or name and options
1948 * suite.add('foo', {
1950 * 'onCycle': onCycle,
1951 * 'onComplete': onComplete
1954 * // or options only
1958 * 'onCycle': onCycle,
1959 * 'onComplete': onComplete
1962 function add(name, fn, options) {
1964 bench = Benchmark(name, fn, options),
1965 event = Event({ 'type': 'add', 'target': bench });
1967 if (me.emit(event), !event.cancelled) {
1974 * Creates a new suite with cloned benchmarks.
1977 * @memberOf Benchmark.Suite
1978 * @param {Object} options Options object to overwrite cloned options.
1979 * @returns {Object} The new suite instance.
1981 function cloneSuite(options) {
1983 result = new me.constructor(extend({}, me.options, options));
1985 // copy own properties
1986 forOwn(me, function(value, key) {
1987 if (!hasKey(result, key)) {
1988 result[key] = value && isClassOf(value.clone, 'Function')
1997 * An `Array#filter` like method.
2000 * @memberOf Benchmark.Suite
2001 * @param {Function|String} callback The function/alias called per iteration.
2002 * @returns {Object} A new suite of benchmarks that passed callback filter.
2004 function filterSuite(callback) {
2006 result = new me.constructor;
2008 result.push.apply(result, filter(me, callback));
2013 * Resets all benchmarks in the suite.
2016 * @memberOf Benchmark.Suite
2017 * @returns {Object} The suite instance.
2019 function resetSuite() {
2022 aborting = calledBy.abortSuite;
2024 if (me.running && !aborting) {
2025 // no worries, `resetSuite()` is called within `abortSuite()`
2026 calledBy.resetSuite = true;
2028 delete calledBy.resetSuite;
2030 // reset if the state has changed
2031 else if ((me.aborted || me.running) &&
2032 (me.emit(event = Event('reset')), !event.cancelled)) {
2035 invoke(me, 'reset');
2045 * @memberOf Benchmark.Suite
2046 * @param {Object} [options={}] Options object.
2047 * @returns {Object} The suite instance.
2053 * // or with options
2054 * suite.run({ 'async': true, 'queued': true });
2056 function runSuite(options) {
2061 options || (options = {});
2066 'queued': options.queued,
2067 'onStart': function(event) {
2070 'onCycle': function(event) {
2071 var bench = event.target;
2073 me.emit({ 'type': 'error', 'target': bench });
2076 event.aborted = me.aborted;
2078 'onComplete': function(event) {
2086 /*--------------------------------------------------------------------------*/
2089 * Executes all registered listeners of the specified event type.
2091 * @memberOf Benchmark, Benchmark.Suite
2092 * @param {String|Object} type The event type or object.
2093 * @returns {Mixed} Returns the return value of the last listener executed.
2095 function emit(type) {
2098 event = Event(type),
2100 args = (arguments[0] = event, arguments);
2102 event.currentTarget || (event.currentTarget = me);
2103 event.target || (event.target = me);
2104 delete event.result;
2106 if (events && (listeners = hasKey(events, event.type) && events[event.type])) {
2107 forEach(listeners.slice(), function(listener) {
2108 if ((event.result = listener.apply(me, args)) === false) {
2109 event.cancelled = true;
2111 return !event.aborted;
2114 return event.result;
2118 * Returns an array of event listeners for a given type that can be manipulated
2119 * to add or remove listeners.
2121 * @memberOf Benchmark, Benchmark.Suite
2122 * @param {String} type The event type.
2123 * @returns {Array} The listeners array.
2125 function listeners(type) {
2127 events = me.events || (me.events = {});
2129 return hasKey(events, type) ? events[type] : (events[type] = []);
2133 * Unregisters a listener for the specified event type(s),
2134 * or unregisters all listeners for the specified event type(s),
2135 * or unregisters all listeners for all event types.
2137 * @memberOf Benchmark, Benchmark.Suite
2138 * @param {String} [type] The event type.
2139 * @param {Function} [listener] The function to unregister.
2140 * @returns {Object} The benchmark instance.
2143 * // unregister a listener for an event type
2144 * bench.off('cycle', listener);
2146 * // unregister a listener for multiple event types
2147 * bench.off('start cycle', listener);
2149 * // unregister all listeners for an event type
2150 * bench.off('cycle');
2152 * // unregister all listeners for multiple event types
2153 * bench.off('start cycle complete');
2155 * // unregister all listeners for all event types
2158 function off(type, listener) {
2162 events && each(type ? type.split(' ') : events, function(listeners, type) {
2164 if (typeof listeners == 'string') {
2166 listeners = hasKey(events, type) && events[type];
2170 index = indexOf(listeners, listener);
2172 listeners.splice(index, 1);
2175 listeners.length = 0;
2183 * Registers a listener for the specified event type(s).
2185 * @memberOf Benchmark, Benchmark.Suite
2186 * @param {String} type The event type.
2187 * @param {Function} listener The function to register.
2188 * @returns {Object} The benchmark instance.
2191 * // register a listener for an event type
2192 * bench.on('cycle', listener);
2194 * // register a listener for multiple event types
2195 * bench.on('start cycle', listener);
2197 function on(type, listener) {
2199 events = me.events || (me.events = {});
2201 forEach(type.split(' '), function(type) {
2202 (hasKey(events, type)
2204 : (events[type] = [])
2210 /*--------------------------------------------------------------------------*/
2213 * Aborts the benchmark without recording times.
2215 * @memberOf Benchmark
2216 * @returns {Object} The benchmark instance.
2221 resetting = calledBy.reset;
2224 event = Event('abort');
2226 if (!event.cancelled || resetting) {
2227 // avoid infinite recursion
2228 calledBy.abort = true;
2230 delete calledBy.abort;
2232 if (support.timeout) {
2233 clearTimeout(me._timerId);
2246 * Creates a new benchmark using the same test and options.
2248 * @memberOf Benchmark
2249 * @param {Object} options Options object to overwrite cloned options.
2250 * @returns {Object} The new benchmark instance.
2253 * var bizarro = bench.clone({
2254 * 'name': 'doppelganger'
2257 function clone(options) {
2259 result = new me.constructor(extend({}, me, options));
2261 // correct the `options` object
2262 result.options = extend({}, me.options, options);
2264 // copy own custom properties
2265 forOwn(me, function(value, key) {
2266 if (!hasKey(result, key)) {
2267 result[key] = deepClone(value);
2274 * Determines if a benchmark is faster than another.
2276 * @memberOf Benchmark
2277 * @param {Object} other The benchmark to compare.
2278 * @returns {Number} Returns `-1` if slower, `1` if faster, and `0` if indeterminate.
2280 function compare(other) {
2284 sample1 = me.stats.sample,
2285 sample2 = other.stats.sample,
2286 size1 = sample1.length,
2287 size2 = sample2.length,
2288 maxSize = max(size1, size2),
2289 minSize = min(size1, size2),
2290 u1 = getU(sample1, sample2),
2291 u2 = getU(sample2, sample1),
2294 function getScore(xA, sampleB) {
2295 return reduce(sampleB, function(total, xB) {
2296 return total + (xB > xA ? 0 : xB < xA ? 1 : 0.5);
2300 function getU(sampleA, sampleB) {
2301 return reduce(sampleA, function(total, xA) {
2302 return total + getScore(xA, sampleB);
2307 return (u - ((size1 * size2) / 2)) / sqrt((size1 * size2 * (size1 + size2 + 1)) / 12);
2310 // exit early if comparing the same benchmark
2314 // reject the null hyphothesis the two samples come from the
2315 // same population (i.e. have the same median) if...
2316 if (size1 + size2 > 30) {
2317 // ...the z-stat is greater than 1.96 or less than -1.96
2318 // http://www.statisticslectures.com/topics/mannwhitneyu/
2320 return abs(zStat) > 1.96 ? (zStat > 0 ? -1 : 1) : 0;
2322 // ...the U value is less than or equal the critical U value
2323 // http://www.geoib.com/mann-whitney-u-test.html
2324 critical = maxSize < 5 || minSize < 3 ? 0 : uTable[maxSize][minSize - 3];
2325 return u <= critical ? (u == u1 ? 1 : -1) : 0;
2329 * Reset properties and abort if running.
2331 * @memberOf Benchmark
2332 * @returns {Object} The benchmark instance.
2339 changes = { 'length': 0 },
2340 queue = { 'length': 0 };
2342 if (me.running && !calledBy.abort) {
2343 // no worries, `reset()` is called within `abort()`
2344 calledBy.reset = true;
2346 delete calledBy.reset;
2349 // a non-recursive solution to check if properties have changed
2350 // http://www.jslab.dk/articles/non.recursive.preorder.traversal.part4
2351 data = { 'destination': me, 'source': extend({}, me.constructor.prototype, me.options) };
2353 forOwn(data.source, function(value, key) {
2355 destination = data.destination,
2356 currValue = destination[key];
2358 if (value && typeof value == 'object') {
2359 if (isClassOf(value, 'Array')) {
2360 // check if an array value has changed to a non-array value
2361 if (!isClassOf(currValue, 'Array')) {
2362 changed = currValue = [];
2364 // or has changed its length
2365 if (currValue.length != value.length) {
2366 changed = currValue = currValue.slice(0, value.length);
2367 currValue.length = value.length;
2370 // check if an object has changed to a non-object value
2371 else if (!currValue || typeof currValue != 'object') {
2372 changed = currValue = {};
2374 // register a changed object
2376 changes[changes.length++] = { 'destination': destination, 'key': key, 'value': currValue };
2378 queue[queue.length++] = { 'destination': currValue, 'source': value };
2380 // register a changed primitive
2381 else if (value !== currValue && !(value == null || isClassOf(value, 'Function'))) {
2382 changes[changes.length++] = { 'destination': destination, 'key': key, 'value': value };
2386 while ((data = queue[index++]));
2388 // if changed emit the `reset` event and if it isn't cancelled reset the benchmark
2389 if (changes.length && (me.emit(event = Event('reset')), !event.cancelled)) {
2390 forEach(changes, function(data) {
2391 data.destination[data.key] = data.value;
2399 * Displays relevant benchmark information when coerced to a string.
2402 * @memberOf Benchmark
2403 * @returns {String} A string representation of the benchmark instance.
2405 function toStringBench() {
2411 size = stats.sample.length,
2412 pm = support.java ? '+/-' : '\xb1',
2413 result = me.name || (isNaN(id) ? id : '<Test #' + id + '>');
2416 result += ': ' + join(error);
2418 result += ' x ' + formatNumber(hz.toFixed(hz < 100 ? 2 : 0)) + ' ops/sec ' + pm +
2419 stats.rme.toFixed(2) + '% (' + size + ' run' + (size == 1 ? '' : 's') + ' sampled)';
2424 /*--------------------------------------------------------------------------*/
2427 * Clocks the time taken to execute a test per cycle (secs).
2430 * @param {Object} bench The benchmark instance.
2431 * @returns {Number} The time taken.
2435 options = Benchmark.options,
2436 template = { 'begin': 's$=new n$', 'end': 'r$=(new n$-s$)/1e3', 'uid': uid },
2437 timers = [{ 'ns': timer.ns, 'res': max(0.0015, getRes('ms')), 'unit': 'ms' }];
2439 // lazy define for hi-res timers
2440 clock = function(clone) {
2442 if (clone instanceof Deferred) {
2444 clone = deferred.benchmark;
2447 var bench = clone._original,
2449 fnArg = deferred ? getFirstArgument(fn) || 'deferred' : '',
2450 stringable = isStringable(fn);
2453 'setup': getSource(bench.setup, preprocess('m$.setup()')),
2454 'fn': getSource(fn, preprocess('m$.fn(' + fnArg + ')')),
2456 'teardown': getSource(bench.teardown, preprocess('m$.teardown()'))
2459 var count = bench.count = clone.count,
2460 decompilable = support.decompilation || stringable,
2462 isEmpty = !(source.fn || stringable),
2463 name = bench.name || (typeof id == 'number' ? '<Test #' + id + '>' : id),
2467 // init `minTime` if needed
2468 clone.minTime = bench.minTime || (bench.minTime = bench.options.minTime = options.minTime);
2470 // repair nanosecond timer
2471 // (some Chrome builds erase the `ns` variable after millions of executions)
2476 // use non-element to avoid issues with libs that augment them
2477 ns = timer.ns = new applet.Packages.nano;
2481 // Compile in setup/teardown functions and the test loop.
2482 // Create a new compiled test, instead of using the cached `bench.compiled`,
2483 // to avoid potential engine optimizations enabled over the life of the test.
2484 var compiled = bench.compiled = createFunction(preprocess('t$'), interpolate(
2486 ? 'var d$=this,#{fnArg}=d$,m$=d$.benchmark._original,f$=m$.fn,su$=m$.setup,td$=m$.teardown;' +
2487 // when `deferred.cycles` is `0` then...
2489 // set `deferred.fn`
2490 'd$.fn=function(){var #{fnArg}=d$;if(typeof f$=="function"){try{#{fn}\n}catch(e$){f$(d$)}}else{#{fn}\n}};' +
2491 // set `deferred.teardown`
2492 'd$.teardown=function(){d$.cycles=0;if(typeof td$=="function"){try{#{teardown}\n}catch(e$){td$()}}else{#{teardown}\n}};' +
2493 // execute the benchmark's `setup`
2494 'if(typeof su$=="function"){try{#{setup}\n}catch(e$){su$()}}else{#{setup}\n};' +
2497 // execute `deferred.fn` and return a dummy object
2500 : 'var r$,s$,m$=this,f$=m$.fn,i$=m$.count,n$=t$.ns;#{setup}\n#{begin};' +
2501 'while(i$--){#{fn}\n}#{end};#{teardown}\nreturn{elapsed:r$,uid:"#{uid}"}'),
2507 // Firefox may remove dead code from Function#toString results
2508 // http://bugzil.la/536085
2509 throw new Error('The test "' + name + '" is empty. This may be the result of dead code removal.');
2511 else if (!deferred) {
2512 // pretest to determine if compiled code is exits early, usually by a
2513 // rogue `return` statement, by checking for a return object with the uid
2515 compiled = (compiled.call(bench, timer) || {}).uid == uid && compiled;
2516 bench.count = count;
2520 clone.error = e || new Error(String(e));
2521 bench.count = count;
2523 // fallback when a test exits early or errors during pretest
2524 if (decompilable && !compiled && !deferred && !isEmpty) {
2525 compiled = createFunction(preprocess('t$'), interpolate(
2527 (clone.error && !stringable
2528 ? 'var r$,s$,m$=this,f$=m$.fn,i$=m$.count'
2529 : 'function f$(){#{fn}\n}var r$,s$,m$=this,i$=m$.count'
2531 ',n$=t$.ns;#{setup}\n#{begin};m$.f$=f$;while(i$--){m$.f$()}#{end};' +
2532 'delete m$.f$;#{teardown}\nreturn{elapsed:r$}'
2538 // pretest one more time to check for errors
2540 compiled.call(bench, timer);
2541 bench.compiled = compiled;
2542 bench.count = count;
2546 bench.count = count;
2550 bench.compiled = compiled;
2551 clone.error = e || new Error(String(e));
2555 // assign `compiled` to `clone` before calling in case a deferred benchmark
2556 // immediately calls `deferred.resolve()`
2557 clone.compiled = compiled;
2558 // if no errors run the full test loop
2560 result = compiled.call(deferred || bench, timer).elapsed;
2565 /*------------------------------------------------------------------------*/
2568 * Gets the current timer's minimum resolution (secs).
2570 function getRes(unit) {
2578 // get average smallest measurable time
2584 while (!(measured = ns.microseconds())) { }
2585 } else if (ns[perfName]) {
2587 measured = Function('n', 'var r,s=n.' + perfName + '();while(!(r=n.' + perfName + '()-s)){};return r')(ns);
2590 while (!(measured = ns() - begin)) { }
2593 else if (unit == 'ns') {
2596 begin = ns.nanoTime();
2597 while (!(measured = ns.nanoTime() - begin)) { }
2599 begin = (begin = ns())[0] + (begin[1] / divisor);
2600 while (!(measured = ((measured = ns())[0] + (measured[1] / divisor)) - begin)) { }
2606 while (!(measured = new ns - begin)) { }
2608 // check for broken timers (nanoTime may have issues)
2609 // http://alivebutsleepy.srnet.cz/unreliable-system-nanotime/
2611 sample.push(measured);
2613 sample.push(Infinity);
2617 // convert to seconds
2618 return getMean(sample) / divisor;
2622 * Replaces all occurrences of `$` with a unique number and
2623 * template tokens with content.
2625 function preprocess(code) {
2626 return interpolate(code, template).replace(/\$/g, /\d+/.exec(uid));
2629 /*------------------------------------------------------------------------*/
2631 // detect nanosecond support from a Java applet
2632 each(doc && doc.applets || [], function(element) {
2633 return !(timer.ns = applet = 'nanoTime' in element && element);
2636 // check type in case Safari returns an object instead of a number
2638 if (typeof timer.ns.nanoTime() == 'number') {
2639 timers.push({ 'ns': timer.ns, 'res': getRes('ns'), 'unit': 'ns' });
2643 // detect Chrome's microsecond timer:
2644 // enable benchmarking via the --enable-benchmarking command
2645 // line switch in at least Chrome 7 to use chrome.Interval
2647 if ((timer.ns = new (window.chrome || window.chromium).Interval)) {
2648 timers.push({ 'ns': timer.ns, 'res': getRes('us'), 'unit': 'us' });
2652 // detect `performance.now` microsecond resolution timer
2653 if ((timer.ns = perfName && perfObject)) {
2654 timers.push({ 'ns': timer.ns, 'res': getRes('us'), 'unit': 'us' });
2657 // detect Node's nanosecond resolution timer available in Node >= 0.8
2658 if (processObject && typeof (timer.ns = processObject.hrtime) == 'function') {
2659 timers.push({ 'ns': timer.ns, 'res': getRes('ns'), 'unit': 'ns' });
2662 // detect Wade Simmons' Node microtime module
2663 if (microtimeObject && typeof (timer.ns = microtimeObject.now) == 'function') {
2664 timers.push({ 'ns': timer.ns, 'res': getRes('us'), 'unit': 'us' });
2667 // pick timer with highest resolution
2668 timer = reduce(timers, function(timer, other) {
2669 return other.res < timer.res ? other : timer;
2672 // remove unused applet
2673 if (timer.unit != 'ns' && applet) {
2674 applet = destroyElement(applet);
2676 // error if there are no working timers
2677 if (timer.res == Infinity) {
2678 throw new Error('Benchmark.js was unable to find a working timer.');
2680 // use API of chosen timer
2681 if (timer.unit == 'ns') {
2682 if (timer.ns.nanoTime) {
2684 'begin': 's$=n$.nanoTime()',
2685 'end': 'r$=(n$.nanoTime()-s$)/1e9'
2690 'end': 'r$=n$(s$);r$=r$[0]+(r$[1]/1e9)'
2694 else if (timer.unit == 'us') {
2695 if (timer.ns.stop) {
2697 'begin': 's$=n$.start()',
2698 'end': 'r$=n$.microseconds()/1e6'
2700 } else if (perfName) {
2702 'begin': 's$=n$.' + perfName + '()',
2703 'end': 'r$=(n$.' + perfName + '()-s$)/1e3'
2708 'end': 'r$=(n$()-s$)/1e6'
2713 // define `timer` methods
2714 timer.start = createFunction(preprocess('o$'),
2715 preprocess('var n$=this.ns,#{begin};o$.elapsed=0;o$.timeStamp=s$'));
2717 timer.stop = createFunction(preprocess('o$'),
2718 preprocess('var n$=this.ns,s$=o$.timeStamp,#{end};o$.elapsed=r$'));
2720 // resolve time span required to achieve a percent uncertainty of at most 1%
2721 // http://spiff.rit.edu/classes/phys273/uncert/uncert.html
2722 options.minTime || (options.minTime = max(timer.res / 2 / 0.01, 0.05));
2723 return clock.apply(null, arguments);
2726 /*--------------------------------------------------------------------------*/
2729 * Computes stats on benchmark results.
2732 * @param {Object} bench The benchmark instance.
2733 * @param {Object} options The options object.
2735 function compute(bench, options) {
2736 options || (options = {});
2738 var async = options.async,
2740 initCount = bench.initCount,
2741 minSamples = bench.minSamples,
2743 sample = bench.stats.sample;
2746 * Adds a clone to the queue.
2748 function enqueue() {
2749 queue.push(bench.clone({
2761 * Updates the clone/original benchmarks to keep their data in sync.
2763 function update(event) {
2767 if (bench.running) {
2768 if (type == 'start') {
2769 // Note: `clone.minTime` prop is inited in `clock()`
2770 clone.count = bench.initCount;
2773 if (type == 'error') {
2774 bench.error = clone.error;
2776 if (type == 'abort') {
2778 bench.emit('cycle');
2780 event.currentTarget = event.target = bench;
2784 } else if (bench.aborted) {
2785 // clear abort listeners to avoid triggering bench's abort/cycle again
2786 clone.events.abort.length = 0;
2792 * Determines if more clones should be queued or if cycling should stop.
2794 function evaluate(event) {
2803 clone = event.target,
2804 done = bench.aborted,
2806 size = sample.push(clone.times.period),
2807 maxedOut = size >= minSamples && (elapsed += now - clone.times.timeStamp) / 1e3 > bench.maxTime,
2808 times = bench.times,
2809 varOf = function(sum, x) { return sum + pow(x - mean, 2); };
2811 // exit early for aborted or unclockable tests
2812 if (done || clone.hz == Infinity) {
2813 maxedOut = !(size = sample.length = queue.length = 0);
2817 // sample mean (estimate of the population mean)
2818 mean = getMean(sample);
2819 // sample variance (estimate of the population variance)
2820 variance = reduce(sample, varOf, 0) / (size - 1) || 0;
2821 // sample standard deviation (estimate of the population standard deviation)
2822 sd = sqrt(variance);
2823 // standard error of the mean (a.k.a. the standard deviation of the sampling distribution of the sample mean)
2824 sem = sd / sqrt(size);
2825 // degrees of freedom
2828 critical = tTable[Math.round(df) || 1] || tTable.infinity;
2830 moe = sem * critical;
2831 // relative margin of error
2832 rme = (moe / mean) * 100 || 0;
2834 extend(bench.stats, {
2840 'variance': variance
2843 // Abort the cycle loop when the minimum sample size has been collected
2844 // and the elapsed time exceeds the maximum time allowed per benchmark.
2845 // We don't count cycle delays toward the max time because delays may be
2846 // increased by browsers that clamp timeouts for inactive tabs.
2847 // https://developer.mozilla.org/en/window.setTimeout#Inactive_tabs
2849 // reset the `initCount` in case the benchmark is rerun
2850 bench.initCount = initCount;
2851 bench.running = false;
2853 times.elapsed = (now - times.timeStamp) / 1e3;
2855 if (bench.hz != Infinity) {
2856 bench.hz = 1 / mean;
2857 times.cycle = mean * bench.count;
2858 times.period = mean;
2861 // if time permits, increase sample size to reduce the margin of error
2862 if (queue.length < 2 && !maxedOut) {
2865 // abort the invoke cycle when done
2866 event.aborted = done;
2869 // init queue and begin
2873 'args': { 'async': async },
2875 'onCycle': evaluate,
2876 'onComplete': function() { bench.emit('complete'); }
2880 /*--------------------------------------------------------------------------*/
2883 * Cycles a benchmark until a run `count` can be established.
2886 * @param {Object} clone The cloned benchmark instance.
2887 * @param {Object} options The options object.
2889 function cycle(clone, options) {
2890 options || (options = {});
2893 if (clone instanceof Deferred) {
2895 clone = clone.benchmark;
2904 async = options.async,
2905 bench = clone._original,
2906 count = clone.count,
2907 times = clone.times;
2909 // continue, if not aborted between cycles
2910 if (clone.running) {
2911 // `minTime` is set to `Benchmark.options.minTime` in `clock()`
2912 cycles = ++clone.cycles;
2913 clocked = deferred ? deferred.elapsed : clock(clone);
2914 minTime = clone.minTime;
2916 if (cycles > bench.cycles) {
2917 bench.cycles = cycles;
2920 event = Event('error');
2921 event.message = clone.error;
2923 if (!event.cancelled) {
2929 // continue, if not errored
2930 if (clone.running) {
2931 // time taken to complete last test cycle
2932 bench.times.cycle = times.cycle = clocked;
2933 // seconds per operation
2934 period = bench.times.period = times.period = clocked / count;
2936 bench.hz = clone.hz = 1 / period;
2937 // avoid working our way up to this next time
2938 bench.initCount = clone.initCount = count;
2939 // do we need to do another cycle?
2940 clone.running = clocked < minTime;
2942 if (clone.running) {
2943 // tests may clock at `0` when `initCount` is a small number,
2944 // to avoid that we set its count to something a bit higher
2945 if (!clocked && (divisor = divisors[clone.cycles]) != null) {
2946 count = floor(4e6 / divisor);
2948 // calculate how many more iterations it will take to achive the `minTime`
2949 if (count <= clone.count) {
2950 count += Math.ceil((minTime - clocked) / period);
2952 clone.running = count != Infinity;
2955 // should we exit early?
2956 event = Event('cycle');
2958 if (event.aborted) {
2961 // figure out what to do next
2962 if (clone.running) {
2963 // start a new cycle
2964 clone.count = count;
2966 clone.compiled.call(deferred, timer);
2968 delay(clone, function() { cycle(clone, options); });
2974 // fix TraceMonkey bug associated with clock fallbacks
2975 // http://bugzil.la/509069
2976 if (support.browser) {
2977 runScript(uid + '=1;delete ' + uid);
2980 clone.emit('complete');
2984 /*--------------------------------------------------------------------------*/
2987 * Runs the benchmark.
2989 * @memberOf Benchmark
2990 * @param {Object} [options={}] Options object.
2991 * @returns {Object} The benchmark instance.
2997 * // or with options
2998 * bench.run({ 'async': true });
3000 function run(options) {
3002 event = Event('start');
3004 // set `running` to `false` so `reset()` won't call `abort()`
3009 me.count = me.initCount;
3010 me.times.timeStamp = +new Date;
3013 if (!event.cancelled) {
3014 options = { 'async': ((options = options && options.async) == null ? me.async : options) && support.timeout };
3016 // for clones created within `compute()`
3024 // for original benchmarks
3026 compute(me, options);
3032 /*--------------------------------------------------------------------------*/
3034 // Firefox 1 erroneously defines variable and argument names of functions on
3035 // the function itself as non-configurable properties with `undefined` values.
3036 // The bugginess continues as the `Benchmark` constructor has an argument
3037 // named `options` and Firefox 1 will not assign a value to `Benchmark.options`,
3038 // making it non-writable in the process, unless it is the first property
3039 // assigned by for-in loop of `extend()`.
3043 * The default options copied by benchmark instances.
3046 * @memberOf Benchmark
3052 * A flag to indicate that benchmark cycles will execute asynchronously
3055 * @memberOf Benchmark.options
3061 * A flag to indicate that the benchmark clock is deferred.
3063 * @memberOf Benchmark.options
3069 * The delay between test cycles (secs).
3070 * @memberOf Benchmark.options
3076 * Displayed by Benchmark#toString when a `name` is not available
3077 * (auto-generated if absent).
3079 * @memberOf Benchmark.options
3085 * The default number of times to execute a test on a benchmark's first cycle.
3087 * @memberOf Benchmark.options
3093 * The maximum time a benchmark is allowed to run before finishing (secs).
3095 * Note: Cycle delays aren't counted toward the maximum time.
3097 * @memberOf Benchmark.options
3103 * The minimum sample size required to perform statistical analysis.
3105 * @memberOf Benchmark.options
3111 * The time needed to reduce the percent uncertainty of measurement to 1% (secs).
3113 * @memberOf Benchmark.options
3119 * The name of the benchmark.
3121 * @memberOf Benchmark.options
3127 * An event listener called when the benchmark is aborted.
3129 * @memberOf Benchmark.options
3132 'onAbort': undefined,
3135 * An event listener called when the benchmark completes running.
3137 * @memberOf Benchmark.options
3140 'onComplete': undefined,
3143 * An event listener called after each run cycle.
3145 * @memberOf Benchmark.options
3148 'onCycle': undefined,
3151 * An event listener called when a test errors.
3153 * @memberOf Benchmark.options
3156 'onError': undefined,
3159 * An event listener called when the benchmark is reset.
3161 * @memberOf Benchmark.options
3164 'onReset': undefined,
3167 * An event listener called when the benchmark starts running.
3169 * @memberOf Benchmark.options
3172 'onStart': undefined
3176 * Platform object with properties describing things like browser name,
3177 * version, and operating system.
3180 * @memberOf Benchmark
3183 'platform': req('platform') || window.platform || {
3186 * The platform description.
3188 * @memberOf Benchmark.platform
3191 'description': window.navigator && navigator.userAgent || null,
3194 * The name of the browser layout engine.
3196 * @memberOf Benchmark.platform
3202 * The name of the product hosting the browser.
3204 * @memberOf Benchmark.platform
3210 * The name of the browser/environment.
3212 * @memberOf Benchmark.platform
3218 * The name of the product's manufacturer.
3220 * @memberOf Benchmark.platform
3223 'manufacturer': null,
3226 * The name of the operating system.
3228 * @memberOf Benchmark.platform
3234 * The alpha/beta release indicator.
3236 * @memberOf Benchmark.platform
3242 * The browser/environment version.
3244 * @memberOf Benchmark.platform
3250 * Return platform description when the platform object is coerced to a string.
3252 * @memberOf Benchmark.platform
3254 * @returns {String} The platform description.
3256 'toString': function() {
3257 return this.description || '';
3262 * The semantic version number.
3265 * @memberOf Benchmark
3270 // an object of environment/feature detection flags
3274 'deepClone': deepClone,
3276 // iteration utility
3282 // generic Array#filter
3285 // generic Array#forEach
3288 // generic own property iteration utility
3291 // converts a number to a comma-separated string
3292 'formatNumber': formatNumber,
3294 // generic Object#hasOwnProperty
3295 // (trigger hasKey's lazy define before assigning it to Benchmark)
3296 'hasKey': (hasKey(Benchmark, ''), hasKey),
3298 // generic Array#indexOf
3302 'interpolate': interpolate,
3304 // invokes a method on each item in an array
3307 // generic Array#join for arrays and objects
3310 // generic Array#map
3313 // retrieves a property value from each item in an array
3316 // generic Array#reduce
3320 /*--------------------------------------------------------------------------*/
3322 extend(Benchmark.prototype, {
3325 * The number of times a test was executed.
3327 * @memberOf Benchmark
3333 * The number of cycles performed while benchmarking.
3335 * @memberOf Benchmark
3341 * The number of executions per second.
3343 * @memberOf Benchmark
3349 * The compiled test function.
3351 * @memberOf Benchmark
3352 * @type Function|String
3354 'compiled': undefined,
3357 * The error object if the test failed.
3359 * @memberOf Benchmark
3365 * The test to benchmark.
3367 * @memberOf Benchmark
3368 * @type Function|String
3373 * A flag to indicate if the benchmark is aborted.
3375 * @memberOf Benchmark
3381 * A flag to indicate if the benchmark is running.
3383 * @memberOf Benchmark
3389 * Compiled into the test and executed immediately **before** the test loop.
3391 * @memberOf Benchmark
3392 * @type Function|String
3396 * var bench = Benchmark({
3397 * 'setup': function() {
3398 * var c = this.count,
3399 * element = document.getElementById('container');
3401 * element.appendChild(document.createElement('div'));
3404 * 'fn': function() {
3405 * element.removeChild(element.lastChild);
3409 * // compiles to something like:
3410 * var c = this.count,
3411 * element = document.getElementById('container');
3413 * element.appendChild(document.createElement('div'));
3415 * var start = new Date;
3417 * element.removeChild(element.lastChild);
3419 * var end = new Date - start;
3421 * // or using strings
3422 * var bench = Benchmark({
3435 * // compiles to something like:
3440 * var start = new Date;
3444 * var end = new Date - start;
3452 * Compiled into the test and executed immediately **after** the test loop.
3454 * @memberOf Benchmark
3455 * @type Function|String
3460 * An object of stats including mean, margin or error, and standard deviation.
3462 * @memberOf Benchmark
3468 * The margin of error.
3470 * @memberOf Benchmark#stats
3476 * The relative margin of error (expressed as a percentage of the mean).
3478 * @memberOf Benchmark#stats
3484 * The standard error of the mean.
3486 * @memberOf Benchmark#stats
3492 * The sample standard deviation.
3494 * @memberOf Benchmark#stats
3500 * The sample arithmetic mean.
3502 * @memberOf Benchmark#stats
3508 * The array of sampled periods.
3510 * @memberOf Benchmark#stats
3516 * The sample variance.
3518 * @memberOf Benchmark#stats
3525 * An object of timing data including cycle, elapsed, period, start, and stop.
3527 * @memberOf Benchmark
3533 * The time taken to complete the last cycle (secs).
3535 * @memberOf Benchmark#times
3541 * The time taken to complete the benchmark (secs).
3543 * @memberOf Benchmark#times
3549 * The time taken to execute the test once (secs).
3551 * @memberOf Benchmark#times
3557 * A timestamp of when the benchmark started (ms).
3559 * @memberOf Benchmark#times
3565 // aborts benchmark (does not record times)
3568 // creates a new benchmark using the same test and options
3571 // compares benchmark's hertz with another
3574 // executes listeners
3578 'listeners': listeners,
3580 // unregister listeners
3583 // register listeners
3586 // reset benchmark properties
3589 // runs the benchmark
3592 // pretty print benchmark info
3593 'toString': toStringBench
3596 /*--------------------------------------------------------------------------*/
3598 extend(Deferred.prototype, {
3601 * The deferred benchmark instance.
3603 * @memberOf Benchmark.Deferred
3609 * The number of deferred cycles performed while benchmarking.
3611 * @memberOf Benchmark.Deferred
3617 * The time taken to complete the deferred benchmark (secs).
3619 * @memberOf Benchmark.Deferred
3625 * A timestamp of when the deferred benchmark started (ms).
3627 * @memberOf Benchmark.Deferred
3632 // cycles/completes the deferred benchmark
3636 /*--------------------------------------------------------------------------*/
3638 extend(Event.prototype, {
3641 * A flag to indicate if the emitters listener iteration is aborted.
3643 * @memberOf Benchmark.Event
3649 * A flag to indicate if the default action is cancelled.
3651 * @memberOf Benchmark.Event
3657 * The object whose listeners are currently being processed.
3659 * @memberOf Benchmark.Event
3662 'currentTarget': undefined,
3665 * The return value of the last executed listener.
3667 * @memberOf Benchmark.Event
3670 'result': undefined,
3673 * The object to which the event was originally emitted.
3675 * @memberOf Benchmark.Event
3678 'target': undefined,
3681 * A timestamp of when the event was created (ms).
3683 * @memberOf Benchmark.Event
3691 * @memberOf Benchmark.Event
3697 /*--------------------------------------------------------------------------*/
3700 * The default options copied by suite instances.
3703 * @memberOf Benchmark.Suite
3709 * The name of the suite.
3711 * @memberOf Benchmark.Suite.options
3717 /*--------------------------------------------------------------------------*/
3719 extend(Suite.prototype, {
3722 * The number of benchmarks in the suite.
3724 * @memberOf Benchmark.Suite
3730 * A flag to indicate if the suite is aborted.
3732 * @memberOf Benchmark.Suite
3738 * A flag to indicate if the suite is running.
3740 * @memberOf Benchmark.Suite
3746 * An `Array#forEach` like method.
3747 * Callbacks may terminate the loop by explicitly returning `false`.
3749 * @memberOf Benchmark.Suite
3750 * @param {Function} callback The function called per iteration.
3751 * @returns {Object} The suite iterated over.
3753 'forEach': methodize(forEach),
3756 * An `Array#indexOf` like method.
3758 * @memberOf Benchmark.Suite
3759 * @param {Mixed} value The value to search for.
3760 * @returns {Number} The index of the matched value or `-1`.
3762 'indexOf': methodize(indexOf),
3765 * Invokes a method on all benchmarks in the suite.
3767 * @memberOf Benchmark.Suite
3768 * @param {String|Object} name The name of the method to invoke OR options object.
3769 * @param {Mixed} [arg1, arg2, ...] Arguments to invoke the method with.
3770 * @returns {Array} A new array of values returned from each method invoked.
3772 'invoke': methodize(invoke),
3775 * Converts the suite of benchmarks to a string.
3777 * @memberOf Benchmark.Suite
3778 * @param {String} [separator=','] A string to separate each element of the array.
3779 * @returns {String} The string.
3784 * An `Array#map` like method.
3786 * @memberOf Benchmark.Suite
3787 * @param {Function} callback The function called per iteration.
3788 * @returns {Array} A new array of values returned by the callback.
3790 'map': methodize(map),
3793 * Retrieves the value of a specified property from all benchmarks in the suite.
3795 * @memberOf Benchmark.Suite
3796 * @param {String} property The property to pluck.
3797 * @returns {Array} A new array of property values.
3799 'pluck': methodize(pluck),
3802 * Removes the last benchmark from the suite and returns it.
3804 * @memberOf Benchmark.Suite
3805 * @returns {Mixed} The removed benchmark.
3810 * Appends benchmarks to the suite.
3812 * @memberOf Benchmark.Suite
3813 * @returns {Number} The suite's new length.
3818 * Sorts the benchmarks of the suite.
3820 * @memberOf Benchmark.Suite
3821 * @param {Function} [compareFn=null] A function that defines the sort order.
3822 * @returns {Object} The sorted suite.
3827 * An `Array#reduce` like method.
3829 * @memberOf Benchmark.Suite
3830 * @param {Function} callback The function called per iteration.
3831 * @param {Mixed} accumulator Initial value of the accumulator.
3832 * @returns {Mixed} The accumulator.
3834 'reduce': methodize(reduce),
3836 // aborts all benchmarks in the suite
3837 'abort': abortSuite,
3839 // adds a benchmark to the suite
3842 // creates a new suite with cloned benchmarks
3843 'clone': cloneSuite,
3845 // executes listeners of a specified type
3848 // creates a new suite of filtered benchmarks
3849 'filter': filterSuite,
3852 'listeners': listeners,
3854 // unregister listeners
3857 // register listeners
3860 // resets all benchmarks in the suite
3861 'reset': resetSuite,
3863 // runs all benchmarks in the suite
3880 /*--------------------------------------------------------------------------*/
3882 // expose Deferred, Event and Suite
3884 'Deferred': Deferred,
3890 // some AMD build optimizers, like r.js, check for specific condition patterns like the following:
3891 if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
3892 // define as an anonymous module so, through path mapping, it can be aliased
3897 // check for `exports` after `define` in case a build optimizer adds an `exports` object
3898 else if (freeExports) {
3899 // in Node.js or RingoJS v0.8.0+
3900 if (typeof module == 'object' && module && module.exports == freeExports) {
3901 (module.exports = Benchmark).Benchmark = Benchmark;
3903 // in Narwhal or RingoJS v0.7.0-
3905 freeExports.Benchmark = Benchmark;
3908 // in a browser or Rhino
3910 // use square bracket notation so Closure Compiler won't munge `Benchmark`
3911 // http://code.google.com/closure/compiler/docs/api-tutorial3.html#export
3912 window['Benchmark'] = Benchmark;
3915 // trigger clock's lazy define early to avoid a security error
3917 clock({ '_original': { 'fn': noop, 'count': 1, 'options': {} } });
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list