You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3918 lines
111 KiB

  1. /*!
  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>
  7. */
  8. ;(function(window, undefined) {
  9. 'use strict';
  10. /** Used to assign each benchmark an incrimented id */
  11. var counter = 0;
  12. /** Detect DOM document object */
  13. var doc = isHostType(window, 'document') && document;
  14. /** Detect free variable `define` */
  15. var freeDefine = typeof define == 'function' &&
  16. typeof define.amd == 'object' && define.amd && define;
  17. /** Detect free variable `exports` */
  18. var freeExports = typeof exports == 'object' && exports &&
  19. (typeof global == 'object' && global && global == global.global && (window = global), exports);
  20. /** Detect free variable `require` */
  21. var freeRequire = typeof require == 'function' && require;
  22. /** Used to crawl all properties regardless of enumerability */
  23. var getAllKeys = Object.getOwnPropertyNames;
  24. /** Used to get property descriptors */
  25. var getDescriptor = Object.getOwnPropertyDescriptor;
  26. /** Used in case an object doesn't have its own method */
  27. var hasOwnProperty = {}.hasOwnProperty;
  28. /** Used to check if an object is extensible */
  29. var isExtensible = Object.isExtensible || function() { return true; };
  30. /** Used to access Wade Simmons' Node microtime module */
  31. var microtimeObject = req('microtime');
  32. /** Used to access the browser's high resolution timer */
  33. var perfObject = isHostType(window, 'performance') && performance;
  34. /** Used to call the browser's high resolution timer */
  35. var perfName = perfObject && (
  36. perfObject.now && 'now' ||
  37. perfObject.webkitNow && 'webkitNow'
  38. );
  39. /** Used to access Node's high resolution timer */
  40. var processObject = isHostType(window, 'process') && process;
  41. /** Used to check if an own property is enumerable */
  42. var propertyIsEnumerable = {}.propertyIsEnumerable;
  43. /** Used to set property descriptors */
  44. var setDescriptor = Object.defineProperty;
  45. /** Used to resolve a value's internal [[Class]] */
  46. var toString = {}.toString;
  47. /** Used to prevent a `removeChild` memory leak in IE < 9 */
  48. var trash = doc && doc.createElement('div');
  49. /** Used to integrity check compiled tests */
  50. var uid = 'uid' + (+new Date);
  51. /** Used to avoid infinite recursion when methods call each other */
  52. var calledBy = {};
  53. /** Used to avoid hz of Infinity */
  54. var divisors = {
  55. '1': 4096,
  56. '2': 512,
  57. '3': 64,
  58. '4': 8,
  59. '5': 0
  60. };
  61. /**
  62. * T-Distribution two-tailed critical values for 95% confidence
  63. * http://www.itl.nist.gov/div898/handbook/eda/section3/eda3672.htm
  64. */
  65. var tTable = {
  66. '1': 12.706,'2': 4.303, '3': 3.182, '4': 2.776, '5': 2.571, '6': 2.447,
  67. '7': 2.365, '8': 2.306, '9': 2.262, '10': 2.228, '11': 2.201, '12': 2.179,
  68. '13': 2.16, '14': 2.145, '15': 2.131, '16': 2.12, '17': 2.11, '18': 2.101,
  69. '19': 2.093, '20': 2.086, '21': 2.08, '22': 2.074, '23': 2.069, '24': 2.064,
  70. '25': 2.06, '26': 2.056, '27': 2.052, '28': 2.048, '29': 2.045, '30': 2.042,
  71. 'infinity': 1.96
  72. };
  73. /**
  74. * Critical Mann-Whitney U-values for 95% confidence
  75. * http://www.saburchill.com/IBbiology/stats/003.html
  76. */
  77. var uTable = {
  78. '5': [0, 1, 2],
  79. '6': [1, 2, 3, 5],
  80. '7': [1, 3, 5, 6, 8],
  81. '8': [2, 4, 6, 8, 10, 13],
  82. '9': [2, 4, 7, 10, 12, 15, 17],
  83. '10': [3, 5, 8, 11, 14, 17, 20, 23],
  84. '11': [3, 6, 9, 13, 16, 19, 23, 26, 30],
  85. '12': [4, 7, 11, 14, 18, 22, 26, 29, 33, 37],
  86. '13': [4, 8, 12, 16, 20, 24, 28, 33, 37, 41, 45],
  87. '14': [5, 9, 13, 17, 22, 26, 31, 36, 40, 45, 50, 55],
  88. '15': [5, 10, 14, 19, 24, 29, 34, 39, 44, 49, 54, 59, 64],
  89. '16': [6, 11, 15, 21, 26, 31, 37, 42, 47, 53, 59, 64, 70, 75],
  90. '17': [6, 11, 17, 22, 28, 34, 39, 45, 51, 57, 63, 67, 75, 81, 87],
  91. '18': [7, 12, 18, 24, 30, 36, 42, 48, 55, 61, 67, 74, 80, 86, 93, 99],
  92. '19': [7, 13, 19, 25, 32, 38, 45, 52, 58, 65, 72, 78, 85, 92, 99, 106, 113],
  93. '20': [8, 14, 20, 27, 34, 41, 48, 55, 62, 69, 76, 83, 90, 98, 105, 112, 119, 127],
  94. '21': [8, 15, 22, 29, 36, 43, 50, 58, 65, 73, 80, 88, 96, 103, 111, 119, 126, 134, 142],
  95. '22': [9, 16, 23, 30, 38, 45, 53, 61, 69, 77, 85, 93, 101, 109, 117, 125, 133, 141, 150, 158],
  96. '23': [9, 17, 24, 32, 40, 48, 56, 64, 73, 81, 89, 98, 106, 115, 123, 132, 140, 149, 157, 166, 175],
  97. '24': [10, 17, 25, 33, 42, 50, 59, 67, 76, 85, 94, 102, 111, 120, 129, 138, 147, 156, 165, 174, 183, 192],
  98. '25': [10, 18, 27, 35, 44, 53, 62, 71, 80, 89, 98, 107, 117, 126, 135, 145, 154, 163, 173, 182, 192, 201, 211],
  99. '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],
  100. '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],
  101. '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],
  102. '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],
  103. '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]
  104. };
  105. /**
  106. * An object used to flag environments/features.
  107. *
  108. * @static
  109. * @memberOf Benchmark
  110. * @type Object
  111. */
  112. var support = {};
  113. (function() {
  114. /**
  115. * Detect Adobe AIR.
  116. *
  117. * @memberOf Benchmark.support
  118. * @type Boolean
  119. */
  120. support.air = isClassOf(window.runtime, 'ScriptBridgingProxyObject');
  121. /**
  122. * Detect if `arguments` objects have the correct internal [[Class]] value.
  123. *
  124. * @memberOf Benchmark.support
  125. * @type Boolean
  126. */
  127. support.argumentsClass = isClassOf(arguments, 'Arguments');
  128. /**
  129. * Detect if in a browser environment.
  130. *
  131. * @memberOf Benchmark.support
  132. * @type Boolean
  133. */
  134. support.browser = doc && isHostType(window, 'navigator');
  135. /**
  136. * Detect if strings support accessing characters by index.
  137. *
  138. * @memberOf Benchmark.support
  139. * @type Boolean
  140. */
  141. support.charByIndex =
  142. // IE 8 supports indexes on string literals but not string objects
  143. ('x'[0] + Object('x')[0]) == 'xx';
  144. /**
  145. * Detect if strings have indexes as own properties.
  146. *
  147. * @memberOf Benchmark.support
  148. * @type Boolean
  149. */
  150. support.charByOwnIndex =
  151. // Narwhal, Rhino, RingoJS, IE 8, and Opera < 10.52 support indexes on
  152. // strings but don't detect them as own properties
  153. support.charByIndex && hasKey('x', '0');
  154. /**
  155. * Detect if Java is enabled/exposed.
  156. *
  157. * @memberOf Benchmark.support
  158. * @type Boolean
  159. */
  160. support.java = isClassOf(window.java, 'JavaPackage');
  161. /**
  162. * Detect if the Timers API exists.
  163. *
  164. * @memberOf Benchmark.support
  165. * @type Boolean
  166. */
  167. support.timeout = isHostType(window, 'setTimeout') && isHostType(window, 'clearTimeout');
  168. /**
  169. * Detect if functions support decompilation.
  170. *
  171. * @name decompilation
  172. * @memberOf Benchmark.support
  173. * @type Boolean
  174. */
  175. try {
  176. // Safari 2.x removes commas in object literals
  177. // from Function#toString results
  178. // http://webk.it/11609
  179. // Firefox 3.6 and Opera 9.25 strip grouping
  180. // parentheses from Function#toString results
  181. // http://bugzil.la/559438
  182. support.decompilation = Function(
  183. 'return (' + (function(x) { return { 'x': '' + (1 + x) + '', 'y': 0 }; }) + ')'
  184. )()(0).x === '1';
  185. } catch(e) {
  186. support.decompilation = false;
  187. }
  188. /**
  189. * Detect ES5+ property descriptor API.
  190. *
  191. * @name descriptors
  192. * @memberOf Benchmark.support
  193. * @type Boolean
  194. */
  195. try {
  196. var o = {};
  197. support.descriptors = (setDescriptor(o, o, o), 'value' in getDescriptor(o, o));
  198. } catch(e) {
  199. support.descriptors = false;
  200. }
  201. /**
  202. * Detect ES5+ Object.getOwnPropertyNames().
  203. *
  204. * @name getAllKeys
  205. * @memberOf Benchmark.support
  206. * @type Boolean
  207. */
  208. try {
  209. support.getAllKeys = /\bvalueOf\b/.test(getAllKeys(Object.prototype));
  210. } catch(e) {
  211. support.getAllKeys = false;
  212. }
  213. /**
  214. * Detect if own properties are iterated before inherited properties (all but IE < 9).
  215. *
  216. * @name iteratesOwnLast
  217. * @memberOf Benchmark.support
  218. * @type Boolean
  219. */
  220. support.iteratesOwnFirst = (function() {
  221. var props = [];
  222. function ctor() { this.x = 1; }
  223. ctor.prototype = { 'y': 1 };
  224. for (var prop in new ctor) { props.push(prop); }
  225. return props[0] == 'x';
  226. }());
  227. /**
  228. * Detect if a node's [[Class]] is resolvable (all but IE < 9)
  229. * and that the JS engine errors when attempting to coerce an object to a
  230. * string without a `toString` property value of `typeof` "function".
  231. *
  232. * @name nodeClass
  233. * @memberOf Benchmark.support
  234. * @type Boolean
  235. */
  236. try {
  237. support.nodeClass = ({ 'toString': 0 } + '', toString.call(doc || 0) != '[object Object]');
  238. } catch(e) {
  239. support.nodeClass = true;
  240. }
  241. }());
  242. /**
  243. * Timer object used by `clock()` and `Deferred#resolve`.
  244. *
  245. * @private
  246. * @type Object
  247. */
  248. var timer = {
  249. /**
  250. * The timer namespace object or constructor.
  251. *
  252. * @private
  253. * @memberOf timer
  254. * @type Function|Object
  255. */
  256. 'ns': Date,
  257. /**
  258. * Starts the deferred timer.
  259. *
  260. * @private
  261. * @memberOf timer
  262. * @param {Object} deferred The deferred instance.
  263. */
  264. 'start': null, // lazy defined in `clock()`
  265. /**
  266. * Stops the deferred timer.
  267. *
  268. * @private
  269. * @memberOf timer
  270. * @param {Object} deferred The deferred instance.
  271. */
  272. 'stop': null // lazy defined in `clock()`
  273. };
  274. /** Shortcut for inverse results */
  275. var noArgumentsClass = !support.argumentsClass,
  276. noCharByIndex = !support.charByIndex,
  277. noCharByOwnIndex = !support.charByOwnIndex;
  278. /** Math shortcuts */
  279. var abs = Math.abs,
  280. floor = Math.floor,
  281. max = Math.max,
  282. min = Math.min,
  283. pow = Math.pow,
  284. sqrt = Math.sqrt;
  285. /*--------------------------------------------------------------------------*/
  286. /**
  287. * The Benchmark constructor.
  288. *
  289. * @constructor
  290. * @param {String} name A name to identify the benchmark.
  291. * @param {Function|String} fn The test to benchmark.
  292. * @param {Object} [options={}] Options object.
  293. * @example
  294. *
  295. * // basic usage (the `new` operator is optional)
  296. * var bench = new Benchmark(fn);
  297. *
  298. * // or using a name first
  299. * var bench = new Benchmark('foo', fn);
  300. *
  301. * // or with options
  302. * var bench = new Benchmark('foo', fn, {
  303. *
  304. * // displayed by Benchmark#toString if `name` is not available
  305. * 'id': 'xyz',
  306. *
  307. * // called when the benchmark starts running
  308. * 'onStart': onStart,
  309. *
  310. * // called after each run cycle
  311. * 'onCycle': onCycle,
  312. *
  313. * // called when aborted
  314. * 'onAbort': onAbort,
  315. *
  316. * // called when a test errors
  317. * 'onError': onError,
  318. *
  319. * // called when reset
  320. * 'onReset': onReset,
  321. *
  322. * // called when the benchmark completes running
  323. * 'onComplete': onComplete,
  324. *
  325. * // compiled/called before the test loop
  326. * 'setup': setup,
  327. *
  328. * // compiled/called after the test loop
  329. * 'teardown': teardown
  330. * });
  331. *
  332. * // or name and options
  333. * var bench = new Benchmark('foo', {
  334. *
  335. * // a flag to indicate the benchmark is deferred
  336. * 'defer': true,
  337. *
  338. * // benchmark test function
  339. * 'fn': function(deferred) {
  340. * // call resolve() when the deferred test is finished
  341. * deferred.resolve();
  342. * }
  343. * });
  344. *
  345. * // or options only
  346. * var bench = new Benchmark({
  347. *
  348. * // benchmark name
  349. * 'name': 'foo',
  350. *
  351. * // benchmark test as a string
  352. * 'fn': '[1,2,3,4].sort()'
  353. * });
  354. *
  355. * // a test's `this` binding is set to the benchmark instance
  356. * var bench = new Benchmark('foo', function() {
  357. * 'My name is '.concat(this.name); // My name is foo
  358. * });
  359. */
  360. function Benchmark(name, fn, options) {
  361. var me = this;
  362. // allow instance creation without the `new` operator
  363. if (me == null || me.constructor != Benchmark) {
  364. return new Benchmark(name, fn, options);
  365. }
  366. // juggle arguments
  367. if (isClassOf(name, 'Object')) {
  368. // 1 argument (options)
  369. options = name;
  370. }
  371. else if (isClassOf(name, 'Function')) {
  372. // 2 arguments (fn, options)
  373. options = fn;
  374. fn = name;
  375. }
  376. else if (isClassOf(fn, 'Object')) {
  377. // 2 arguments (name, options)
  378. options = fn;
  379. fn = null;
  380. me.name = name;
  381. }
  382. else {
  383. // 3 arguments (name, fn [, options])
  384. me.name = name;
  385. }
  386. setOptions(me, options);
  387. me.id || (me.id = ++counter);
  388. me.fn == null && (me.fn = fn);
  389. me.stats = deepClone(me.stats);
  390. me.times = deepClone(me.times);
  391. }
  392. /**
  393. * The Deferred constructor.
  394. *
  395. * @constructor
  396. * @memberOf Benchmark
  397. * @param {Object} clone The cloned benchmark instance.
  398. */
  399. function Deferred(clone) {
  400. var me = this;
  401. if (me == null || me.constructor != Deferred) {
  402. return new Deferred(clone);
  403. }
  404. me.benchmark = clone;
  405. clock(me);
  406. }
  407. /**
  408. * The Event constructor.
  409. *
  410. * @constructor
  411. * @memberOf Benchmark
  412. * @param {String|Object} type The event type.
  413. */
  414. function Event(type) {
  415. var me = this;
  416. return (me == null || me.constructor != Event)
  417. ? new Event(type)
  418. : (type instanceof Event)
  419. ? type
  420. : extend(me, { 'timeStamp': +new Date }, typeof type == 'string' ? { 'type': type } : type);
  421. }
  422. /**
  423. * The Suite constructor.
  424. *
  425. * @constructor
  426. * @memberOf Benchmark
  427. * @param {String} name A name to identify the suite.
  428. * @param {Object} [options={}] Options object.
  429. * @example
  430. *
  431. * // basic usage (the `new` operator is optional)
  432. * var suite = new Benchmark.Suite;
  433. *
  434. * // or using a name first
  435. * var suite = new Benchmark.Suite('foo');
  436. *
  437. * // or with options
  438. * var suite = new Benchmark.Suite('foo', {
  439. *
  440. * // called when the suite starts running
  441. * 'onStart': onStart,
  442. *
  443. * // called between running benchmarks
  444. * 'onCycle': onCycle,
  445. *
  446. * // called when aborted
  447. * 'onAbort': onAbort,
  448. *
  449. * // called when a test errors
  450. * 'onError': onError,
  451. *
  452. * // called when reset
  453. * 'onReset': onReset,
  454. *
  455. * // called when the suite completes running
  456. * 'onComplete': onComplete
  457. * });
  458. */
  459. function Suite(name, options) {
  460. var me = this;
  461. // allow instance creation without the `new` operator
  462. if (me == null || me.constructor != Suite) {
  463. return new Suite(name, options);
  464. }
  465. // juggle arguments
  466. if (isClassOf(name, 'Object')) {
  467. // 1 argument (options)
  468. options = name;
  469. } else {
  470. // 2 arguments (name [, options])
  471. me.name = name;
  472. }
  473. setOptions(me, options);
  474. }
  475. /*--------------------------------------------------------------------------*/
  476. /**
  477. * Note: Some array methods have been implemented in plain JavaScript to avoid
  478. * bugs in IE, Opera, Rhino, and Mobile Safari.
  479. *
  480. * IE compatibility mode and IE < 9 have buggy Array `shift()` and `splice()`
  481. * functions that fail to remove the last element, `object[0]`, of
  482. * array-like-objects even though the `length` property is set to `0`.
  483. * The `shift()` method is buggy in IE 8 compatibility mode, while `splice()`
  484. * is buggy regardless of mode in IE < 9 and buggy in compatibility mode in IE 9.
  485. *
  486. * In Opera < 9.50 and some older/beta Mobile Safari versions using `unshift()`
  487. * generically to augment the `arguments` object will pave the value at index 0
  488. * without incrimenting the other values's indexes.
  489. * https://github.com/documentcloud/underscore/issues/9
  490. *
  491. * Rhino and environments it powers, like Narwhal and RingoJS, may have
  492. * buggy Array `concat()`, `reverse()`, `shift()`, `slice()`, `splice()` and
  493. * `unshift()` functions that make sparse arrays non-sparse by assigning the
  494. * undefined indexes a value of undefined.
  495. * https://github.com/mozilla/rhino/commit/702abfed3f8ca043b2636efd31c14ba7552603dd
  496. */
  497. /**
  498. * Creates an array containing the elements of the host array followed by the
  499. * elements of each argument in order.
  500. *
  501. * @memberOf Benchmark.Suite
  502. * @returns {Array} The new array.
  503. */
  504. function concat() {
  505. var value,
  506. j = -1,
  507. length = arguments.length,
  508. result = slice.call(this),
  509. index = result.length;
  510. while (++j < length) {
  511. value = arguments[j];
  512. if (isClassOf(value, 'Array')) {
  513. for (var k = 0, l = value.length; k < l; k++, index++) {
  514. if (k in value) {
  515. result[index] = value[k];
  516. }
  517. }
  518. } else {
  519. result[index++] = value;
  520. }
  521. }
  522. return result;
  523. }
  524. /**
  525. * Utility function used by `shift()`, `splice()`, and `unshift()`.
  526. *
  527. * @private
  528. * @param {Number} start The index to start inserting elements.
  529. * @param {Number} deleteCount The number of elements to delete from the insert point.
  530. * @param {Array} elements The elements to insert.
  531. * @returns {Array} An array of deleted elements.
  532. */
  533. function insert(start, deleteCount, elements) {
  534. // `result` should have its length set to the `deleteCount`
  535. // see https://bugs.ecmascript.org/show_bug.cgi?id=332
  536. var deleteEnd = start + deleteCount,
  537. elementCount = elements ? elements.length : 0,
  538. index = start - 1,
  539. length = start + elementCount,
  540. object = this,
  541. result = Array(deleteCount),
  542. tail = slice.call(object, deleteEnd);
  543. // delete elements from the array
  544. while (++index < deleteEnd) {
  545. if (index in object) {
  546. result[index - start] = object[index];
  547. delete object[index];
  548. }
  549. }
  550. // insert elements
  551. index = start - 1;
  552. while (++index < length) {
  553. object[index] = elements[index - start];
  554. }
  555. // append tail elements
  556. start = index--;
  557. length = max(0, (object.length >>> 0) - deleteCount + elementCount);
  558. while (++index < length) {
  559. if ((index - start) in tail) {
  560. object[index] = tail[index - start];
  561. } else if (index in object) {
  562. delete object[index];
  563. }
  564. }
  565. // delete excess elements
  566. deleteCount = deleteCount > elementCount ? deleteCount - elementCount : 0;
  567. while (deleteCount--) {
  568. index = length + deleteCount;
  569. if (index in object) {
  570. delete object[index];
  571. }
  572. }
  573. object.length = length;
  574. return result;
  575. }
  576. /**
  577. * Rearrange the host array's elements in reverse order.
  578. *
  579. * @memberOf Benchmark.Suite
  580. * @returns {Array} The reversed array.
  581. */
  582. function reverse() {
  583. var upperIndex,
  584. value,
  585. index = -1,
  586. object = Object(this),
  587. length = object.length >>> 0,
  588. middle = floor(length / 2);
  589. if (length > 1) {
  590. while (++index < middle) {
  591. upperIndex = length - index - 1;
  592. value = upperIndex in object ? object[upperIndex] : uid;
  593. if (index in object) {
  594. object[upperIndex] = object[index];
  595. } else {
  596. delete object[upperIndex];
  597. }
  598. if (value != uid) {
  599. object[index] = value;
  600. } else {
  601. delete object[index];
  602. }
  603. }
  604. }
  605. return object;
  606. }
  607. /**
  608. * Removes the first element of the host array and returns it.
  609. *
  610. * @memberOf Benchmark.Suite
  611. * @returns {Mixed} The first element of the array.
  612. */
  613. function shift() {
  614. return insert.call(this, 0, 1)[0];
  615. }
  616. /**
  617. * Creates an array of the host array's elements from the start index up to,
  618. * but not including, the end index.
  619. *
  620. * @memberOf Benchmark.Suite
  621. * @param {Number} start The starting index.
  622. * @param {Number} end The end index.
  623. * @returns {Array} The new array.
  624. */
  625. function slice(start, end) {
  626. var index = -1,
  627. object = Object(this),
  628. length = object.length >>> 0,
  629. result = [];
  630. start = toInteger(start);
  631. start = start < 0 ? max(length + start, 0) : min(start, length);
  632. start--;
  633. end = end == null ? length : toInteger(end);
  634. end = end < 0 ? max(length + end, 0) : min(end, length);
  635. while ((++index, ++start) < end) {
  636. if (start in object) {
  637. result[index] = object[start];
  638. }
  639. }
  640. return result;
  641. }
  642. /**
  643. * Allows removing a range of elements and/or inserting elements into the
  644. * host array.
  645. *
  646. * @memberOf Benchmark.Suite
  647. * @param {Number} start The start index.
  648. * @param {Number} deleteCount The number of elements to delete.
  649. * @param {Mixed} [val1, val2, ...] values to insert at the `start` index.
  650. * @returns {Array} An array of removed elements.
  651. */
  652. function splice(start, deleteCount) {
  653. var object = Object(this),
  654. length = object.length >>> 0;
  655. start = toInteger(start);
  656. start = start < 0 ? max(length + start, 0) : min(start, length);
  657. // support the de-facto SpiderMonkey extension
  658. // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice#Parameters
  659. // https://bugs.ecmascript.org/show_bug.cgi?id=429
  660. deleteCount = arguments.length == 1
  661. ? length - start
  662. : min(max(toInteger(deleteCount), 0), length - start);
  663. return insert.call(object, start, deleteCount, slice.call(arguments, 2));
  664. }
  665. /**
  666. * Converts the specified `value` to an integer.
  667. *
  668. * @private
  669. * @param {Mixed} value The value to convert.
  670. * @returns {Number} The resulting integer.
  671. */
  672. function toInteger(value) {
  673. value = +value;
  674. return value === 0 || !isFinite(value) ? value || 0 : value - (value % 1);
  675. }
  676. /**
  677. * Appends arguments to the host array.
  678. *
  679. * @memberOf Benchmark.Suite
  680. * @returns {Number} The new length.
  681. */
  682. function unshift() {
  683. var object = Object(this);
  684. insert.call(object, 0, 0, arguments);
  685. return object.length;
  686. }
  687. /*--------------------------------------------------------------------------*/
  688. /**
  689. * A generic `Function#bind` like method.
  690. *
  691. * @private
  692. * @param {Function} fn The function to be bound to `thisArg`.
  693. * @param {Mixed} thisArg The `this` binding for the given function.
  694. * @returns {Function} The bound function.
  695. */
  696. function bind(fn, thisArg) {
  697. return function() { fn.apply(thisArg, arguments); };
  698. }
  699. /**
  700. * Creates a function from the given arguments string and body.
  701. *
  702. * @private
  703. * @param {String} args The comma separated function arguments.
  704. * @param {String} body The function body.
  705. * @returns {Function} The new function.
  706. */
  707. function createFunction() {
  708. // lazy define
  709. createFunction = function(args, body) {
  710. var result,
  711. anchor = freeDefine ? define.amd : Benchmark,
  712. prop = uid + 'createFunction';
  713. runScript((freeDefine ? 'define.amd.' : 'Benchmark.') + prop + '=function(' + args + '){' + body + '}');
  714. result = anchor[prop];
  715. delete anchor[prop];
  716. return result;
  717. };
  718. // fix JaegerMonkey bug
  719. // http://bugzil.la/639720
  720. createFunction = support.browser && (createFunction('', 'return"' + uid + '"') || noop)() == uid ? createFunction : Function;
  721. return createFunction.apply(null, arguments);
  722. }
  723. /**
  724. * Delay the execution of a function based on the benchmark's `delay` property.
  725. *
  726. * @private
  727. * @param {Object} bench The benchmark instance.
  728. * @param {Object} fn The function to execute.
  729. */
  730. function delay(bench, fn) {
  731. bench._timerId = setTimeout(fn, bench.delay * 1e3);
  732. }
  733. /**
  734. * Destroys the given element.
  735. *
  736. * @private
  737. * @param {Element} element The element to destroy.
  738. */
  739. function destroyElement(element) {
  740. trash.appendChild(element);
  741. trash.innerHTML = '';
  742. }
  743. /**
  744. * Iterates over an object's properties, executing the `callback` for each.
  745. * Callbacks may terminate the loop by explicitly returning `false`.
  746. *
  747. * @private
  748. * @param {Object} object The object to iterate over.
  749. * @param {Function} callback The function executed per own property.
  750. * @param {Object} options The options object.
  751. * @returns {Object} Returns the object iterated over.
  752. */
  753. function forProps() {
  754. var forShadowed,
  755. skipSeen,
  756. forArgs = true,
  757. shadowed = ['constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf'];
  758. (function(enumFlag, key) {
  759. // must use a non-native constructor to catch the Safari 2 issue
  760. function Klass() { this.valueOf = 0; };
  761. Klass.prototype.valueOf = 0;
  762. // check various for-in bugs
  763. for (key in new Klass) {
  764. enumFlag += key == 'valueOf' ? 1 : 0;
  765. }
  766. // check if `arguments` objects have non-enumerable indexes
  767. for (key in arguments) {
  768. key == '0' && (forArgs = false);
  769. }
  770. // Safari 2 iterates over shadowed properties twice
  771. // http://replay.waybackmachine.org/20090428222941/http://tobielangel.com/2007/1/29/for-in-loop-broken-in-safari/
  772. skipSeen = enumFlag == 2;
  773. // IE < 9 incorrectly makes an object's properties non-enumerable if they have
  774. // the same name as other non-enumerable properties in its prototype chain.
  775. forShadowed = !enumFlag;
  776. }(0));
  777. // lazy define
  778. forProps = function(object, callback, options) {
  779. options || (options = {});
  780. var result = object;
  781. object = Object(object);
  782. var ctor,
  783. key,
  784. keys,
  785. skipCtor,
  786. done = !result,
  787. which = options.which,
  788. allFlag = which == 'all',
  789. index = -1,
  790. iteratee = object,
  791. length = object.length,
  792. ownFlag = allFlag || which == 'own',
  793. seen = {},
  794. skipProto = isClassOf(object, 'Function'),
  795. thisArg = options.bind;
  796. if (thisArg !== undefined) {
  797. callback = bind(callback, thisArg);
  798. }
  799. // iterate all properties
  800. if (allFlag && support.getAllKeys) {
  801. for (index = 0, keys = getAllKeys(object), length = keys.length; index < length; index++) {
  802. key = keys[index];
  803. if (callback(object[key], key, object) === false) {
  804. break;
  805. }
  806. }
  807. }
  808. // else iterate only enumerable properties
  809. else {
  810. for (key in object) {
  811. // Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1
  812. // (if the prototype or a property on the prototype has been set)
  813. // incorrectly set a function's `prototype` property [[Enumerable]] value
  814. // to `true`. Because of this we standardize on skipping the `prototype`
  815. // property of functions regardless of their [[Enumerable]] value.
  816. if ((done =
  817. !(skipProto && key == 'prototype') &&
  818. !(skipSeen && (hasKey(seen, key) || !(seen[key] = true))) &&
  819. (!ownFlag || ownFlag && hasKey(object, key)) &&
  820. callback(object[key], key, object) === false)) {
  821. break;
  822. }
  823. }
  824. // in IE < 9 strings don't support accessing characters by index
  825. if (!done && (forArgs && isArguments(object) ||
  826. ((noCharByIndex || noCharByOwnIndex) && isClassOf(object, 'String') &&
  827. (iteratee = noCharByIndex ? object.split('') : object)))) {
  828. while (++index < length) {
  829. if ((done =
  830. callback(iteratee[index], String(index), object) === false)) {
  831. break;
  832. }
  833. }
  834. }
  835. if (!done && forShadowed) {
  836. // Because IE < 9 can't set the `[[Enumerable]]` attribute of an existing
  837. // property and the `constructor` property of a prototype defaults to
  838. // non-enumerable, we manually skip the `constructor` property when we
  839. // think we are iterating over a `prototype` object.
  840. ctor = object.constructor;
  841. skipCtor = ctor && ctor.prototype && ctor.prototype.constructor === ctor;
  842. for (index = 0; index < 7; index++) {
  843. key = shadowed[index];
  844. if (!(skipCtor && key == 'constructor') &&
  845. hasKey(object, key) &&
  846. callback(object[key], key, object) === false) {
  847. break;
  848. }
  849. }
  850. }
  851. }
  852. return result;
  853. };
  854. return forProps.apply(null, arguments);
  855. }
  856. /**
  857. * Gets the name of the first argument from a function's source.
  858. *
  859. * @private
  860. * @param {Function} fn The function.
  861. * @returns {String} The argument name.
  862. */
  863. function getFirstArgument(fn) {
  864. return (!hasKey(fn, 'toString') &&
  865. (/^[\s(]*function[^(]*\(([^\s,)]+)/.exec(fn) || 0)[1]) || '';
  866. }
  867. /**
  868. * Computes the arithmetic mean of a sample.
  869. *
  870. * @private
  871. * @param {Array} sample The sample.
  872. * @returns {Number} The mean.
  873. */
  874. function getMean(sample) {
  875. return reduce(sample, function(sum, x) {
  876. return sum + x;
  877. }) / sample.length || 0;
  878. }
  879. /**
  880. * Gets the source code of a function.
  881. *
  882. * @private
  883. * @param {Function} fn The function.
  884. * @param {String} altSource A string used when a function's source code is unretrievable.
  885. * @returns {String} The function's source code.
  886. */
  887. function getSource(fn, altSource) {
  888. var result = altSource;
  889. if (isStringable(fn)) {
  890. result = String(fn);
  891. } else if (support.decompilation) {
  892. // escape the `{` for Firefox 1
  893. result = (/^[^{]+\{([\s\S]*)}\s*$/.exec(fn) || 0)[1];
  894. }
  895. // trim string
  896. result = (result || '').replace(/^\s+|\s+$/g, '');
  897. // detect strings containing only the "use strict" directive
  898. return /^(?:\/\*+[\w|\W]*?\*\/|\/\/.*?[\n\r\u2028\u2029]|\s)*(["'])use strict\1;?$/.test(result)
  899. ? ''
  900. : result;
  901. }
  902. /**
  903. * Checks if a value is an `arguments` object.
  904. *
  905. * @private
  906. * @param {Mixed} value The value to check.
  907. * @returns {Boolean} Returns `true` if the value is an `arguments` object, else `false`.
  908. */
  909. function isArguments() {
  910. // lazy define
  911. isArguments = function(value) {
  912. return toString.call(value) == '[object Arguments]';
  913. };
  914. if (noArgumentsClass) {
  915. isArguments = function(value) {
  916. return hasKey(value, 'callee') &&
  917. !(propertyIsEnumerable && propertyIsEnumerable.call(value, 'callee'));
  918. };
  919. }
  920. return isArguments(arguments[0]);
  921. }
  922. /**
  923. * Checks if an object is of the specified class.
  924. *
  925. * @private
  926. * @param {Mixed} value The value to check.
  927. * @param {String} name The name of the class.
  928. * @returns {Boolean} Returns `true` if the value is of the specified class, else `false`.
  929. */
  930. function isClassOf(value, name) {
  931. return value != null && toString.call(value) == '[object ' + name + ']';
  932. }
  933. /**
  934. * Host objects can return type values that are different from their actual
  935. * data type. The objects we are concerned with usually return non-primitive
  936. * types of object, function, or unknown.
  937. *
  938. * @private
  939. * @param {Mixed} object The owner of the property.
  940. * @param {String} property The property to check.
  941. * @returns {Boolean} Returns `true` if the property value is a non-primitive, else `false`.
  942. */
  943. function isHostType(object, property) {
  944. var type = object != null ? typeof object[property] : 'number';
  945. return !/^(?:boolean|number|string|undefined)$/.test(type) &&
  946. (type == 'object' ? !!object[property] : true);
  947. }
  948. /**
  949. * Checks if a given `value` is an object created by the `Object` constructor
  950. * assuming objects created by the `Object` constructor have no inherited
  951. * enumerable properties and that there are no `Object.prototype` extensions.
  952. *
  953. * @private
  954. * @param {Mixed} value The value to check.
  955. * @returns {Boolean} Returns `true` if the `value` is a plain `Object` object, else `false`.
  956. */
  957. function isPlainObject(value) {
  958. // avoid non-objects and false positives for `arguments` objects in IE < 9
  959. var result = false;
  960. if (!(value && typeof value == 'object') || (noArgumentsClass && isArguments(value))) {
  961. return result;
  962. }
  963. // IE < 9 presents DOM nodes as `Object` objects except they have `toString`
  964. // methods that are `typeof` "string" and still can coerce nodes to strings.
  965. // Also check that the constructor is `Object` (i.e. `Object instanceof Object`)
  966. var ctor = value.constructor;
  967. if ((support.nodeClass || !(typeof value.toString != 'function' && typeof (value + '') == 'string')) &&
  968. (!isClassOf(ctor, 'Function') || ctor instanceof ctor)) {
  969. // In most environments an object's own properties are iterated before
  970. // its inherited properties. If the last iterated property is an object's
  971. // own property then there are no inherited enumerable properties.
  972. if (support.iteratesOwnFirst) {
  973. forProps(value, function(subValue, subKey) {
  974. result = subKey;
  975. });
  976. return result === false || hasKey(value, result);
  977. }
  978. // IE < 9 iterates inherited properties before own properties. If the first
  979. // iterated property is an object's own property then there are no inherited
  980. // enumerable properties.
  981. forProps(value, function(subValue, subKey) {
  982. result = !hasKey(value, subKey);
  983. return false;
  984. });
  985. return result === false;
  986. }
  987. return result;
  988. }
  989. /**
  990. * Checks if a value can be safely coerced to a string.
  991. *
  992. * @private
  993. * @param {Mixed} value The value to check.
  994. * @returns {Boolean} Returns `true` if the value can be coerced, else `false`.
  995. */
  996. function isStringable(value) {
  997. return hasKey(value, 'toString') || isClassOf(value, 'String');
  998. }
  999. /**
  1000. * Wraps a function and passes `this` to the original function as the
  1001. * first argument.
  1002. *
  1003. * @private
  1004. * @param {Function} fn The function to be wrapped.
  1005. * @returns {Function} The new function.
  1006. */
  1007. function methodize(fn) {
  1008. return function() {
  1009. var args = [this];
  1010. args.push.apply(args, arguments);
  1011. return fn.apply(null, args);
  1012. };
  1013. }
  1014. /**
  1015. * A no-operation function.
  1016. *
  1017. * @private
  1018. */
  1019. function noop() {
  1020. // no operation performed
  1021. }
  1022. /**
  1023. * A wrapper around require() to suppress `module missing` errors.
  1024. *
  1025. * @private
  1026. * @param {String} id The module id.
  1027. * @returns {Mixed} The exported module or `null`.
  1028. */
  1029. function req(id) {
  1030. try {
  1031. var result = freeExports && freeRequire(id);
  1032. } catch(e) { }
  1033. return result || null;
  1034. }
  1035. /**
  1036. * Runs a snippet of JavaScript via script injection.
  1037. *
  1038. * @private
  1039. * @param {String} code The code to run.
  1040. */
  1041. function runScript(code) {
  1042. var anchor = freeDefine ? define.amd : Benchmark,
  1043. script = doc.createElement('script'),
  1044. sibling = doc.getElementsByTagName('script')[0],
  1045. parent = sibling.parentNode,
  1046. prop = uid + 'runScript',
  1047. prefix = '(' + (freeDefine ? 'define.amd.' : 'Benchmark.') + prop + '||function(){})();';
  1048. // Firefox 2.0.0.2 cannot use script injection as intended because it executes
  1049. // asynchronously, but that's OK because script injection is only used to avoid
  1050. // the previously commented JaegerMonkey bug.
  1051. try {
  1052. // remove the inserted script *before* running the code to avoid differences
  1053. // in the expected script element count/order of the document.
  1054. script.appendChild(doc.createTextNode(prefix + code));
  1055. anchor[prop] = function() { destroyElement(script); };
  1056. } catch(e) {
  1057. parent = parent.cloneNode(false);
  1058. sibling = null;
  1059. script.text = code;
  1060. }
  1061. parent.insertBefore(script, sibling);
  1062. delete anchor[prop];
  1063. }
  1064. /**
  1065. * A helper function for setting options/event handlers.
  1066. *
  1067. * @private
  1068. * @param {Object} bench The benchmark instance.
  1069. * @param {Object} [options={}] Options object.
  1070. */
  1071. function setOptions(bench, options) {
  1072. options = extend({}, bench.constructor.options, options);
  1073. bench.options = forOwn(options, function(value, key) {
  1074. if (value != null) {
  1075. // add event listeners
  1076. if (/^on[A-Z]/.test(key)) {
  1077. forEach(key.split(' '), function(key) {
  1078. bench.on(key.slice(2).toLowerCase(), value);
  1079. });
  1080. } else if (!hasKey(bench, key)) {
  1081. bench[key] = deepClone(value);
  1082. }
  1083. }
  1084. });
  1085. }
  1086. /*--------------------------------------------------------------------------*/
  1087. /**
  1088. * Handles cycling/completing the deferred benchmark.
  1089. *
  1090. * @memberOf Benchmark.Deferred
  1091. */
  1092. function resolve() {
  1093. var me = this,
  1094. clone = me.benchmark,
  1095. bench = clone._original;
  1096. if (bench.aborted) {
  1097. // cycle() -> clone cycle/complete event -> compute()'s invoked bench.run() cycle/complete
  1098. me.teardown();
  1099. clone.running = false;
  1100. cycle(me);
  1101. }
  1102. else if (++me.cycles < clone.count) {
  1103. // continue the test loop
  1104. if (support.timeout) {
  1105. // use setTimeout to avoid a call stack overflow if called recursively
  1106. setTimeout(function() { clone.compiled.call(me, timer); }, 0);
  1107. } else {
  1108. clone.compiled.call(me, timer);
  1109. }
  1110. }
  1111. else {
  1112. timer.stop(me);
  1113. me.teardown();
  1114. delay(clone, function() { cycle(me); });
  1115. }
  1116. }
  1117. /*--------------------------------------------------------------------------*/
  1118. /**
  1119. * A deep clone utility.
  1120. *
  1121. * @static
  1122. * @memberOf Benchmark
  1123. * @param {Mixed} value The value to clone.
  1124. * @returns {Mixed} The cloned value.
  1125. */
  1126. function deepClone(value) {
  1127. var accessor,
  1128. circular,
  1129. clone,
  1130. ctor,
  1131. descriptor,
  1132. extensible,
  1133. key,
  1134. length,
  1135. markerKey,
  1136. parent,
  1137. result,
  1138. source,
  1139. subIndex,
  1140. data = { 'value': value },
  1141. index = 0,
  1142. marked = [],
  1143. queue = { 'length': 0 },
  1144. unmarked = [];
  1145. /**
  1146. * An easily detectable decorator for cloned values.
  1147. */
  1148. function Marker(object) {
  1149. this.raw = object;
  1150. }
  1151. /**
  1152. * The callback used by `forProps()`.
  1153. */
  1154. function forPropsCallback(subValue, subKey) {
  1155. // exit early to avoid cloning the marker
  1156. if (subValue && subValue.constructor == Marker) {
  1157. return;
  1158. }
  1159. // add objects to the queue
  1160. if (subValue === Object(subValue)) {
  1161. queue[queue.length++] = { 'key': subKey, 'parent': clone, 'source': value };
  1162. }
  1163. // assign non-objects
  1164. else {
  1165. try {
  1166. // will throw an error in strict mode if the property is read-only
  1167. clone[subKey] = subValue;
  1168. } catch(e) { }
  1169. }
  1170. }
  1171. /**
  1172. * Gets an available marker key for the given object.
  1173. */
  1174. function getMarkerKey(object) {
  1175. // avoid collisions with existing keys
  1176. var result = uid;
  1177. while (object[result] && object[result].constructor != Marker) {
  1178. result += 1;
  1179. }
  1180. return result;
  1181. }
  1182. do {
  1183. key = data.key;
  1184. parent = data.parent;
  1185. source = data.source;
  1186. clone = value = source ? source[key] : data.value;
  1187. accessor = circular = descriptor = false;
  1188. // create a basic clone to filter out functions, DOM elements, and
  1189. // other non `Object` objects
  1190. if (value === Object(value)) {
  1191. // use custom deep clone function if available
  1192. if (isClassOf(value.deepClone, 'Function')) {
  1193. clone = value.deepClone();
  1194. } else {
  1195. ctor = value.constructor;
  1196. switch (toString.call(value)) {
  1197. case '[object Array]':
  1198. clone = new ctor(value.length);
  1199. break;
  1200. case '[object Boolean]':
  1201. clone = new ctor(value == true);
  1202. break;
  1203. case '[object Date]':
  1204. clone = new ctor(+value);
  1205. break;
  1206. case '[object Object]':
  1207. isPlainObject(value) && (clone = {});
  1208. break;
  1209. case '[object Number]':
  1210. case '[object String]':
  1211. clone = new ctor(value);
  1212. break;
  1213. case '[object RegExp]':
  1214. clone = ctor(value.source,
  1215. (value.global ? 'g' : '') +
  1216. (value.ignoreCase ? 'i' : '') +
  1217. (value.multiline ? 'm' : ''));
  1218. }
  1219. }
  1220. // continue clone if `value` doesn't have an accessor descriptor
  1221. // http://es5.github.com/#x8.10.1
  1222. if (clone && clone != value &&
  1223. !(descriptor = source && support.descriptors && getDescriptor(source, key),
  1224. accessor = descriptor && (descriptor.get || descriptor.set))) {
  1225. // use an existing clone (circular reference)
  1226. if ((extensible = isExtensible(value))) {
  1227. markerKey = getMarkerKey(value);
  1228. if (value[markerKey]) {
  1229. circular = clone = value[markerKey].raw;
  1230. }
  1231. } else {
  1232. // for frozen/sealed objects
  1233. for (subIndex = 0, length = unmarked.length; subIndex < length; subIndex++) {
  1234. data = unmarked[subIndex];
  1235. if (data.object === value) {
  1236. circular = clone = data.clone;
  1237. break;
  1238. }
  1239. }
  1240. }
  1241. if (!circular) {
  1242. // mark object to allow quickly detecting circular references and tie it to its clone
  1243. if (extensible) {
  1244. value[markerKey] = new Marker(clone);
  1245. marked.push({ 'key': markerKey, 'object': value });
  1246. } else {
  1247. // for frozen/sealed objects
  1248. unmarked.push({ 'clone': clone, 'object': value });
  1249. }
  1250. // iterate over object properties
  1251. forProps(value, forPropsCallback, { 'which': 'all' });
  1252. }
  1253. }
  1254. }
  1255. if (parent) {
  1256. // for custom property descriptors
  1257. if (accessor || (descriptor && !(descriptor.configurable && descriptor.enumerable && descriptor.writable))) {
  1258. if ('value' in descriptor) {
  1259. descriptor.value = clone;
  1260. }
  1261. setDescriptor(parent, key, descriptor);
  1262. }
  1263. // for default property descriptors
  1264. else {
  1265. parent[key] = clone;
  1266. }
  1267. } else {
  1268. result = clone;
  1269. }
  1270. } while ((data = queue[index++]));
  1271. // remove markers
  1272. for (index = 0, length = marked.length; index < length; index++) {
  1273. data = marked[index];
  1274. delete data.object[data.key];
  1275. }
  1276. return result;
  1277. }
  1278. /**
  1279. * An iteration utility for arrays and objects.
  1280. * Callbacks may terminate the loop by explicitly returning `false`.
  1281. *
  1282. * @static
  1283. * @memberOf Benchmark
  1284. * @param {Array|Object} object The object to iterate over.
  1285. * @param {Function} callback The function called per iteration.
  1286. * @param {Mixed} thisArg The `this` binding for the callback.
  1287. * @returns {Array|Object} Returns the object iterated over.
  1288. */
  1289. function each(object, callback, thisArg) {
  1290. var result = object;
  1291. object = Object(object);
  1292. var fn = callback,
  1293. index = -1,
  1294. length = object.length,
  1295. isSnapshot = !!(object.snapshotItem && (length = object.snapshotLength)),
  1296. isSplittable = (noCharByIndex || noCharByOwnIndex) && isClassOf(object, 'String'),
  1297. isConvertable = isSnapshot || isSplittable || 'item' in object,
  1298. origObject = object;
  1299. // in Opera < 10.5 `hasKey(object, 'length')` returns `false` for NodeLists
  1300. if (length === length >>> 0) {
  1301. if (isConvertable) {
  1302. // the third argument of the callback is the original non-array object
  1303. callback = function(value, index) {
  1304. return fn.call(this, value, index, origObject);
  1305. };
  1306. // in IE < 9 strings don't support accessing characters by index
  1307. if (isSplittable) {
  1308. object = object.split('');
  1309. } else {
  1310. object = [];
  1311. while (++index < length) {
  1312. // in Safari 2 `index in object` is always `false` for NodeLists
  1313. object[index] = isSnapshot ? result.snapshotItem(index) : result[index];
  1314. }
  1315. }
  1316. }
  1317. forEach(object, callback, thisArg);
  1318. } else {
  1319. forOwn(object, callback, thisArg);
  1320. }
  1321. return result;
  1322. }
  1323. /**
  1324. * Copies enumerable properties from the source(s) object to the destination object.
  1325. *
  1326. * @static
  1327. * @memberOf Benchmark
  1328. * @param {Object} destination The destination object.
  1329. * @param {Object} [source={}] The source object.
  1330. * @returns {Object} The destination object.
  1331. */
  1332. function extend(destination, source) {
  1333. // Chrome < 14 incorrectly sets `destination` to `undefined` when we `delete arguments[0]`
  1334. // http://code.google.com/p/v8/issues/detail?id=839
  1335. var result = destination;
  1336. delete arguments[0];
  1337. forEach(arguments, function(source) {
  1338. forProps(source, function(value, key) {
  1339. result[key] = value;
  1340. });
  1341. });
  1342. return result;
  1343. }
  1344. /**
  1345. * A generic `Array#filter` like method.
  1346. *
  1347. * @static
  1348. * @memberOf Benchmark
  1349. * @param {Array} array The array to iterate over.
  1350. * @param {Function|String} callback The function/alias called per iteration.
  1351. * @param {Mixed} thisArg The `this` binding for the callback.
  1352. * @returns {Array} A new array of values that passed callback filter.
  1353. * @example
  1354. *
  1355. * // get odd numbers
  1356. * Benchmark.filter([1, 2, 3, 4, 5], function(n) {
  1357. * return n % 2;
  1358. * }); // -> [1, 3, 5];
  1359. *
  1360. * // get fastest benchmarks
  1361. * Benchmark.filter(benches, 'fastest');
  1362. *
  1363. * // get slowest benchmarks
  1364. * Benchmark.filter(benches, 'slowest');
  1365. *
  1366. * // get benchmarks that completed without erroring
  1367. * Benchmark.filter(benches, 'successful');
  1368. */
  1369. function filter(array, callback, thisArg) {
  1370. var result;
  1371. if (callback == 'successful') {
  1372. // callback to exclude those that are errored, unrun, or have hz of Infinity
  1373. callback = function(bench) { return bench.cycles && isFinite(bench.hz); };
  1374. }
  1375. else if (callback == 'fastest' || callback == 'slowest') {
  1376. // get successful, sort by period + margin of error, and filter fastest/slowest
  1377. result = filter(array, 'successful').sort(function(a, b) {
  1378. a = a.stats; b = b.stats;
  1379. return (a.mean + a.moe > b.mean + b.moe ? 1 : -1) * (callback == 'fastest' ? 1 : -1);
  1380. });
  1381. result = filter(result, function(bench) {
  1382. return result[0].compare(bench) == 0;
  1383. });
  1384. }
  1385. return result || reduce(array, function(result, value, index) {
  1386. return callback.call(thisArg, value, index, array) ? (result.push(value), result) : result;
  1387. }, []);
  1388. }
  1389. /**
  1390. * A generic `Array#forEach` like method.
  1391. * Callbacks may terminate the loop by explicitly returning `false`.
  1392. *
  1393. * @static
  1394. * @memberOf Benchmark
  1395. * @param {Array} array The array 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} Returns the array iterated over.
  1399. */
  1400. function forEach(array, callback, thisArg) {
  1401. var index = -1,
  1402. length = (array = Object(array)).length >>> 0;
  1403. if (thisArg !== undefined) {
  1404. callback = bind(callback, thisArg);
  1405. }
  1406. while (++index < length) {
  1407. if (index in array &&
  1408. callback(array[index], index, array) === false) {
  1409. break;
  1410. }
  1411. }
  1412. return array;
  1413. }
  1414. /**
  1415. * Iterates over an object's own properties, executing the `callback` for each.
  1416. * Callbacks may terminate the loop by explicitly returning `false`.
  1417. *
  1418. * @static
  1419. * @memberOf Benchmark
  1420. * @param {Object} object The object to iterate over.
  1421. * @param {Function} callback The function executed per own property.
  1422. * @param {Mixed} thisArg The `this` binding for the callback.
  1423. * @returns {Object} Returns the object iterated over.
  1424. */
  1425. function forOwn(object, callback, thisArg) {
  1426. return forProps(object, callback, { 'bind': thisArg, 'which': 'own' });
  1427. }
  1428. /**
  1429. * Converts a number to a more readable comma-separated string representation.
  1430. *
  1431. * @static
  1432. * @memberOf Benchmark
  1433. * @param {Number} number The number to convert.
  1434. * @returns {String} The more readable string representation.
  1435. */
  1436. function formatNumber(number) {
  1437. number = String(number).split('.');
  1438. return number[0].replace(/(?=(?:\d{3})+$)(?!\b)/g, ',') +
  1439. (number[1] ? '.' + number[1] : '');
  1440. }
  1441. /**
  1442. * Checks if an object has the specified key as a direct property.
  1443. *
  1444. * @static
  1445. * @memberOf Benchmark
  1446. * @param {Object} object The object to check.
  1447. * @param {String} key The key to check for.
  1448. * @returns {Boolean} Returns `true` if key is a direct property, else `false`.
  1449. */
  1450. function hasKey() {
  1451. // lazy define for worst case fallback (not as accurate)
  1452. hasKey = function(object, key) {
  1453. var parent = object != null && (object.constructor || Object).prototype;
  1454. return !!parent && key in Object(object) && !(key in parent && object[key] === parent[key]);
  1455. };
  1456. // for modern browsers
  1457. if (isClassOf(hasOwnProperty, 'Function')) {
  1458. hasKey = function(object, key) {
  1459. return object != null && hasOwnProperty.call(object, key);
  1460. };
  1461. }
  1462. // for Safari 2
  1463. else if ({}.__proto__ == Object.prototype) {
  1464. hasKey = function(object, key) {
  1465. var result = false;
  1466. if (object != null) {
  1467. object = Object(object);
  1468. object.__proto__ = [object.__proto__, object.__proto__ = null, result = key in object][0];
  1469. }
  1470. return result;
  1471. };
  1472. }
  1473. return hasKey.apply(this, arguments);
  1474. }
  1475. /**
  1476. * A generic `Array#indexOf` like method.
  1477. *
  1478. * @static
  1479. * @memberOf Benchmark
  1480. * @param {Array} array The array to iterate over.
  1481. * @param {Mixed} value The value to search for.
  1482. * @param {Number} [fromIndex=0] The index to start searching from.
  1483. * @returns {Number} The index of the matched value or `-1`.
  1484. */
  1485. function indexOf(array, value, fromIndex) {
  1486. var index = toInteger(fromIndex),
  1487. length = (array = Object(array)).length >>> 0;
  1488. index = (index < 0 ? max(0, length + index) : index) - 1;
  1489. while (++index < length) {
  1490. if (index in array && value === array[index]) {
  1491. return index;
  1492. }
  1493. }
  1494. return -1;
  1495. }
  1496. /**
  1497. * Modify a string by replacing named tokens with matching object property values.
  1498. *
  1499. * @static
  1500. * @memberOf Benchmark
  1501. * @param {String} string The string to modify.
  1502. * @param {Object} object The template object.
  1503. * @returns {String} The modified string.
  1504. */
  1505. function interpolate(string, object) {
  1506. forOwn(object, function(value, key) {
  1507. // escape regexp special characters in `key`
  1508. string = string.replace(RegExp('#\\{' + key.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1') + '\\}', 'g'), value);
  1509. });
  1510. return string;
  1511. }
  1512. /**
  1513. * Invokes a method on all items in an array.
  1514. *
  1515. * @static
  1516. * @memberOf Benchmark
  1517. * @param {Array} benches Array of benchmarks to iterate over.
  1518. * @param {String|Object} name The name of the method to invoke OR options object.
  1519. * @param {Mixed} [arg1, arg2, ...] Arguments to invoke the method with.
  1520. * @returns {Array} A new array of values returned from each method invoked.
  1521. * @example
  1522. *
  1523. * // invoke `reset` on all benchmarks
  1524. * Benchmark.invoke(benches, 'reset');
  1525. *
  1526. * // invoke `emit` with arguments
  1527. * Benchmark.invoke(benches, 'emit', 'complete', listener);
  1528. *
  1529. * // invoke `run(true)`, treat benchmarks as a queue, and register invoke callbacks
  1530. * Benchmark.invoke(benches, {
  1531. *
  1532. * // invoke the `run` method
  1533. * 'name': 'run',
  1534. *
  1535. * // pass a single argument
  1536. * 'args': true,
  1537. *
  1538. * // treat as queue, removing benchmarks from front of `benches` until empty
  1539. * 'queued': true,
  1540. *
  1541. * // called before any benchmarks have been invoked.
  1542. * 'onStart': onStart,
  1543. *
  1544. * // called between invoking benchmarks
  1545. * 'onCycle': onCycle,
  1546. *
  1547. * // called after all benchmarks have been invoked.
  1548. * 'onComplete': onComplete
  1549. * });
  1550. */
  1551. function invoke(benches, name) {
  1552. var args,
  1553. bench,
  1554. queued,
  1555. index = -1,
  1556. eventProps = { 'currentTarget': benches },
  1557. options = { 'onStart': noop, 'onCycle': noop, 'onComplete': noop },
  1558. result = map(benches, function(bench) { return bench; });
  1559. /**
  1560. * Invokes the method of the current object and if synchronous, fetches the next.
  1561. */
  1562. function execute() {
  1563. var listeners,
  1564. async = isAsync(bench);
  1565. if (async) {
  1566. // use `getNext` as the first listener
  1567. bench.on('complete', getNext);
  1568. listeners = bench.events.complete;
  1569. listeners.splice(0, 0, listeners.pop());
  1570. }
  1571. // execute method
  1572. result[index] = isClassOf(bench && bench[name], 'Function') ? bench[name].apply(bench, args) : undefined;
  1573. // if synchronous return true until finished
  1574. return !async && getNext();
  1575. }
  1576. /**
  1577. * Fetches the next bench or executes `onComplete` callback.
  1578. */
  1579. function getNext(event) {
  1580. var cycleEvent,
  1581. last = bench,
  1582. async = isAsync(last);
  1583. if (async) {
  1584. last.off('complete', getNext);
  1585. last.emit('complete');
  1586. }
  1587. // emit "cycle" event
  1588. eventProps.type = 'cycle';
  1589. eventProps.target = last;
  1590. cycleEvent = Event(eventProps);
  1591. options.onCycle.call(benches, cycleEvent);
  1592. // choose next benchmark if not exiting early
  1593. if (!cycleEvent.aborted && raiseIndex() !== false) {
  1594. bench = queued ? benches[0] : result[index];
  1595. if (isAsync(bench)) {
  1596. delay(bench, execute);
  1597. }
  1598. else if (async) {
  1599. // resume execution if previously asynchronous but now synchronous
  1600. while (execute()) { }
  1601. }
  1602. else {
  1603. // continue synchronous execution
  1604. return true;
  1605. }
  1606. } else {
  1607. // emit "complete" event
  1608. eventProps.type = 'complete';
  1609. options.onComplete.call(benches, Event(eventProps));
  1610. }
  1611. // When used as a listener `event.aborted = true` will cancel the rest of
  1612. // the "complete" listeners because they were already called above and when
  1613. // used as part of `getNext` the `return false` will exit the execution while-loop.
  1614. if (event) {
  1615. event.aborted = true;
  1616. } else {
  1617. return false;
  1618. }
  1619. }
  1620. /**
  1621. * Checks if invoking `Benchmark#run` with asynchronous cycles.
  1622. */
  1623. function isAsync(object) {
  1624. // avoid using `instanceof` here because of IE memory leak issues with host objects
  1625. var async = args[0] && args[0].async;
  1626. return Object(object).constructor == Benchmark && name == 'run' &&
  1627. ((async == null ? object.options.async : async) && support.timeout || object.defer);
  1628. }
  1629. /**
  1630. * Raises `index` to the next defined index or returns `false`.
  1631. */
  1632. function raiseIndex() {
  1633. var length = result.length;
  1634. if (queued) {
  1635. // if queued remove the previous bench and subsequent skipped non-entries
  1636. do {
  1637. ++index > 0 && shift.call(benches);
  1638. } while ((length = benches.length) && !('0' in benches));
  1639. }
  1640. else {
  1641. while (++index < length && !(index in result)) { }
  1642. }
  1643. // if we reached the last index then return `false`
  1644. return (queued ? length : index < length) ? index : (index = false);
  1645. }
  1646. // juggle arguments
  1647. if (isClassOf(name, 'String')) {
  1648. // 2 arguments (array, name)
  1649. args = slice.call(arguments, 2);
  1650. } else {
  1651. // 2 arguments (array, options)
  1652. options = extend(options, name);
  1653. name = options.name;
  1654. args = isClassOf(args = 'args' in options ? options.args : [], 'Array') ? args : [args];
  1655. queued = options.queued;
  1656. }
  1657. // start iterating over the array
  1658. if (raiseIndex() !== false) {
  1659. // emit "start" event
  1660. bench = result[index];
  1661. eventProps.type = 'start';
  1662. eventProps.target = bench;
  1663. options.onStart.call(benches, Event(eventProps));
  1664. // end early if the suite was aborted in an "onStart" listener
  1665. if (benches.aborted && benches.constructor == Suite && name == 'run') {
  1666. // emit "cycle" event
  1667. eventProps.type = 'cycle';
  1668. options.onCycle.call(benches, Event(eventProps));
  1669. // emit "complete" event
  1670. eventProps.type = 'complete';
  1671. options.onComplete.call(benches, Event(eventProps));
  1672. }
  1673. // else start
  1674. else {
  1675. if (isAsync(bench)) {
  1676. delay(bench, execute);
  1677. } else {
  1678. while (execute()) { }
  1679. }
  1680. }
  1681. }
  1682. return result;
  1683. }
  1684. /**
  1685. * Creates a string of joined array values or object key-value pairs.
  1686. *
  1687. * @static
  1688. * @memberOf Benchmark
  1689. * @param {Array|Object} object The object to operate on.
  1690. * @param {String} [separator1=','] The separator used between key-value pairs.
  1691. * @param {String} [separator2=': '] The separator used between keys and values.
  1692. * @returns {String} The joined result.
  1693. */
  1694. function join(object, separator1, separator2) {
  1695. var result = [],
  1696. length = (object = Object(object)).length,
  1697. arrayLike = length === length >>> 0;
  1698. separator2 || (separator2 = ': ');
  1699. each(object, function(value, key) {
  1700. result.push(arrayLike ? value : key + separator2 + value);
  1701. });
  1702. return result.join(separator1 || ',');
  1703. }
  1704. /**
  1705. * A generic `Array#map` like method.
  1706. *
  1707. * @static
  1708. * @memberOf Benchmark
  1709. * @param {Array} array The array to iterate over.
  1710. * @param {Function} callback The function called per iteration.
  1711. * @param {Mixed} thisArg The `this` binding for the callback.
  1712. * @returns {Array} A new array of values returned by the callback.
  1713. */
  1714. function map(array, callback, thisArg) {
  1715. return reduce(array, function(result, value, index) {
  1716. result[index] = callback.call(thisArg, value, index, array);
  1717. return result;
  1718. }, Array(Object(array).length >>> 0));
  1719. }
  1720. /**
  1721. * Retrieves the value of a specified property from all items in an array.
  1722. *
  1723. * @static
  1724. * @memberOf Benchmark
  1725. * @param {Array} array The array to iterate over.
  1726. * @param {String} property The property to pluck.
  1727. * @returns {Array} A new array of property values.
  1728. */
  1729. function pluck(array, property) {
  1730. return map(array, function(object) {
  1731. return object == null ? undefined : object[property];
  1732. });
  1733. }
  1734. /**
  1735. * A generic `Array#reduce` like method.
  1736. *
  1737. * @static
  1738. * @memberOf Benchmark
  1739. * @param {Array} array The array to iterate over.
  1740. * @param {Function} callback The function called per iteration.
  1741. * @param {Mixed} accumulator Initial value of the accumulator.
  1742. * @returns {Mixed} The accumulator.
  1743. */
  1744. function reduce(array, callback, accumulator) {
  1745. var noaccum = arguments.length < 3;
  1746. forEach(array, function(value, index) {
  1747. accumulator = noaccum ? (noaccum = false, value) : callback(accumulator, value, index, array);
  1748. });
  1749. return accumulator;
  1750. }
  1751. /*--------------------------------------------------------------------------*/
  1752. /**
  1753. * Aborts all benchmarks in the suite.
  1754. *
  1755. * @name abort
  1756. * @memberOf Benchmark.Suite
  1757. * @returns {Object} The suite instance.
  1758. */
  1759. function abortSuite() {
  1760. var event,
  1761. me = this,
  1762. resetting = calledBy.resetSuite;
  1763. if (me.running) {
  1764. event = Event('abort');
  1765. me.emit(event);
  1766. if (!event.cancelled || resetting) {
  1767. // avoid infinite recursion
  1768. calledBy.abortSuite = true;
  1769. me.reset();
  1770. delete calledBy.abortSuite;
  1771. if (!resetting) {
  1772. me.aborted = true;
  1773. invoke(me, 'abort');
  1774. }
  1775. }
  1776. }
  1777. return me;
  1778. }
  1779. /**
  1780. * Adds a test to the benchmark suite.
  1781. *
  1782. * @memberOf Benchmark.Suite
  1783. * @param {String} name A name to identify the benchmark.
  1784. * @param {Function|String} fn The test to benchmark.
  1785. * @param {Object} [options={}] Options object.
  1786. * @returns {Object} The benchmark instance.
  1787. * @example
  1788. *
  1789. * // basic usage
  1790. * suite.add(fn);
  1791. *
  1792. * // or using a name first
  1793. * suite.add('foo', fn);
  1794. *
  1795. * // or with options
  1796. * suite.add('foo', fn, {
  1797. * 'onCycle': onCycle,
  1798. * 'onComplete': onComplete
  1799. * });
  1800. *
  1801. * // or name and options
  1802. * suite.add('foo', {
  1803. * 'fn': fn,
  1804. * 'onCycle': onCycle,
  1805. * 'onComplete': onComplete
  1806. * });
  1807. *
  1808. * // or options only
  1809. * suite.add({
  1810. * 'name': 'foo',
  1811. * 'fn': fn,
  1812. * 'onCycle': onCycle,
  1813. * 'onComplete': onComplete
  1814. * });
  1815. */
  1816. function add(name, fn, options) {
  1817. var me = this,
  1818. bench = Benchmark(name, fn, options),
  1819. event = Event({ 'type': 'add', 'target': bench });
  1820. if (me.emit(event), !event.cancelled) {
  1821. me.push(bench);
  1822. }
  1823. return me;
  1824. }
  1825. /**
  1826. * Creates a new suite with cloned benchmarks.
  1827. *
  1828. * @name clone
  1829. * @memberOf Benchmark.Suite
  1830. * @param {Object} options Options object to overwrite cloned options.
  1831. * @returns {Object} The new suite instance.
  1832. */
  1833. function cloneSuite(options) {
  1834. var me = this,
  1835. result = new me.constructor(extend({}, me.options, options));
  1836. // copy own properties
  1837. forOwn(me, function(value, key) {
  1838. if (!hasKey(result, key)) {
  1839. result[key] = value && isClassOf(value.clone, 'Function')
  1840. ? value.clone()
  1841. : deepClone(value);
  1842. }
  1843. });
  1844. return result;
  1845. }
  1846. /**
  1847. * An `Array#filter` like method.
  1848. *
  1849. * @name filter
  1850. * @memberOf Benchmark.Suite
  1851. * @param {Function|String} callback The function/alias called per iteration.
  1852. * @returns {Object} A new suite of benchmarks that passed callback filter.
  1853. */
  1854. function filterSuite(callback) {
  1855. var me = this,
  1856. result = new me.constructor;
  1857. result.push.apply(result, filter(me, callback));
  1858. return result;
  1859. }
  1860. /**
  1861. * Resets all benchmarks in the suite.
  1862. *
  1863. * @name reset
  1864. * @memberOf Benchmark.Suite
  1865. * @returns {Object} The suite instance.
  1866. */
  1867. function resetSuite() {
  1868. var event,
  1869. me = this,
  1870. aborting = calledBy.abortSuite;
  1871. if (me.running && !aborting) {
  1872. // no worries, `resetSuite()` is called within `abortSuite()`
  1873. calledBy.resetSuite = true;
  1874. me.abort();
  1875. delete calledBy.resetSuite;
  1876. }
  1877. // reset if the state has changed
  1878. else if ((me.aborted || me.running) &&
  1879. (me.emit(event = Event('reset')), !event.cancelled)) {
  1880. me.running = false;
  1881. if (!aborting) {
  1882. invoke(me, 'reset');
  1883. }
  1884. }
  1885. return me;
  1886. }
  1887. /**
  1888. * Runs the suite.
  1889. *
  1890. * @name run
  1891. * @memberOf Benchmark.Suite
  1892. * @param {Object} [options={}] Options object.
  1893. * @returns {Object} The suite instance.
  1894. * @example
  1895. *
  1896. * // basic usage
  1897. * suite.run();
  1898. *
  1899. * // or with options
  1900. * suite.run({ 'async': true, 'queued': true });
  1901. */
  1902. function runSuite(options) {
  1903. var me = this;
  1904. me.reset();
  1905. me.running = true;
  1906. options || (options = {});
  1907. invoke(me, {
  1908. 'name': 'run',
  1909. 'args': options,
  1910. 'queued': options.queued,
  1911. 'onStart': function(event) {
  1912. me.emit(event);
  1913. },
  1914. 'onCycle': function(event) {
  1915. var bench = event.target;
  1916. if (bench.error) {
  1917. me.emit({ 'type': 'error', 'target': bench });
  1918. }
  1919. me.emit(event);
  1920. event.aborted = me.aborted;
  1921. },
  1922. 'onComplete': function(event) {
  1923. me.running = false;
  1924. me.emit(event);
  1925. }
  1926. });
  1927. return me;
  1928. }
  1929. /*--------------------------------------------------------------------------*/
  1930. /**
  1931. * Executes all registered listeners of the specified event type.
  1932. *
  1933. * @memberOf Benchmark, Benchmark.Suite
  1934. * @param {String|Object} type The event type or object.
  1935. * @returns {Mixed} Returns the return value of the last listener executed.
  1936. */
  1937. function emit(type) {
  1938. var listeners,
  1939. me = this,
  1940. event = Event(type),
  1941. events = me.events,
  1942. args = (arguments[0] = event, arguments);
  1943. event.currentTarget || (event.currentTarget = me);
  1944. event.target || (event.target = me);
  1945. delete event.result;
  1946. if (events && (listeners = hasKey(events, event.type) && events[event.type])) {
  1947. forEach(listeners.slice(), function(listener) {
  1948. if ((event.result = listener.apply(me, args)) === false) {
  1949. event.cancelled = true;
  1950. }
  1951. return !event.aborted;
  1952. });
  1953. }
  1954. return event.result;
  1955. }
  1956. /**
  1957. * Returns an array of event listeners for a given type that can be manipulated
  1958. * to add or remove listeners.
  1959. *
  1960. * @memberOf Benchmark, Benchmark.Suite
  1961. * @param {String} type The event type.
  1962. * @returns {Array} The listeners array.
  1963. */
  1964. function listeners(type) {
  1965. var me = this,
  1966. events = me.events || (me.events = {});
  1967. return hasKey(events, type) ? events[type] : (events[type] = []);
  1968. }
  1969. /**
  1970. * Unregisters a listener for the specified event type(s),
  1971. * or unregisters all listeners for the specified event type(s),
  1972. * or unregisters all listeners for all event types.
  1973. *
  1974. * @memberOf Benchmark, Benchmark.Suite
  1975. * @param {String} [type] The event type.
  1976. * @param {Function} [listener] The function to unregister.
  1977. * @returns {Object} The benchmark instance.
  1978. * @example
  1979. *
  1980. * // unregister a listener for an event type
  1981. * bench.off('cycle', listener);
  1982. *
  1983. * // unregister a listener for multiple event types
  1984. * bench.off('start cycle', listener);
  1985. *
  1986. * // unregister all listeners for an event type
  1987. * bench.off('cycle');
  1988. *
  1989. * // unregister all listeners for multiple event types
  1990. * bench.off('start cycle complete');
  1991. *
  1992. * // unregister all listeners for all event types
  1993. * bench.off();
  1994. */
  1995. function off(type, listener) {
  1996. var me = this,
  1997. events = me.events;
  1998. events && each(type ? type.split(' ') : events, function(listeners, type) {
  1999. var index;
  2000. if (typeof listeners == 'string') {
  2001. type = listeners;
  2002. listeners = hasKey(events, type) && events[type];
  2003. }
  2004. if (listeners) {
  2005. if (listener) {
  2006. index = indexOf(listeners, listener);
  2007. if (index > -1) {
  2008. listeners.splice(index, 1);
  2009. }
  2010. } else {
  2011. listeners.length = 0;
  2012. }
  2013. }
  2014. });
  2015. return me;
  2016. }
  2017. /**
  2018. * Registers a listener for the specified event type(s).
  2019. *
  2020. * @memberOf Benchmark, Benchmark.Suite
  2021. * @param {String} type The event type.
  2022. * @param {Function} listener The function to register.
  2023. * @returns {Object} The benchmark instance.
  2024. * @example
  2025. *
  2026. * // register a listener for an event type
  2027. * bench.on('cycle', listener);
  2028. *
  2029. * // register a listener for multiple event types
  2030. * bench.on('start cycle', listener);
  2031. */
  2032. function on(type, listener) {
  2033. var me = this,
  2034. events = me.events || (me.events = {});
  2035. forEach(type.split(' '), function(type) {
  2036. (hasKey(events, type)
  2037. ? events[type]
  2038. : (events[type] = [])
  2039. ).push(listener);
  2040. });
  2041. return me;
  2042. }
  2043. /*--------------------------------------------------------------------------*/
  2044. /**
  2045. * Aborts the benchmark without recording times.
  2046. *
  2047. * @memberOf Benchmark
  2048. * @returns {Object} The benchmark instance.
  2049. */
  2050. function abort() {
  2051. var event,
  2052. me = this,
  2053. resetting = calledBy.reset;
  2054. if (me.running) {
  2055. event = Event('abort');
  2056. me.emit(event);
  2057. if (!event.cancelled || resetting) {
  2058. // avoid infinite recursion
  2059. calledBy.abort = true;
  2060. me.reset();
  2061. delete calledBy.abort;
  2062. if (support.timeout) {
  2063. clearTimeout(me._timerId);
  2064. delete me._timerId;
  2065. }
  2066. if (!resetting) {
  2067. me.aborted = true;
  2068. me.running = false;
  2069. }
  2070. }
  2071. }
  2072. return me;
  2073. }
  2074. /**
  2075. * Creates a new benchmark using the same test and options.
  2076. *
  2077. * @memberOf Benchmark
  2078. * @param {Object} options Options object to overwrite cloned options.
  2079. * @returns {Object} The new benchmark instance.
  2080. * @example
  2081. *
  2082. * var bizarro = bench.clone({
  2083. * 'name': 'doppelganger'
  2084. * });
  2085. */
  2086. function clone(options) {
  2087. var me = this,
  2088. result = new me.constructor(extend({}, me, options));
  2089. // correct the `options` object
  2090. result.options = extend({}, me.options, options);
  2091. // copy own custom properties
  2092. forOwn(me, function(value, key) {
  2093. if (!hasKey(result, key)) {
  2094. result[key] = deepClone(value);
  2095. }
  2096. });
  2097. return result;
  2098. }
  2099. /**
  2100. * Determines if a benchmark is faster than another.
  2101. *
  2102. * @memberOf Benchmark
  2103. * @param {Object} other The benchmark to compare.
  2104. * @returns {Number} Returns `-1` if slower, `1` if faster, and `0` if indeterminate.
  2105. */
  2106. function compare(other) {
  2107. var critical,
  2108. zStat,
  2109. me = this,
  2110. sample1 = me.stats.sample,
  2111. sample2 = other.stats.sample,
  2112. size1 = sample1.length,
  2113. size2 = sample2.length,
  2114. maxSize = max(size1, size2),
  2115. minSize = min(size1, size2),
  2116. u1 = getU(sample1, sample2),
  2117. u2 = getU(sample2, sample1),
  2118. u = min(u1, u2);
  2119. function getScore(xA, sampleB) {
  2120. return reduce(sampleB, function(total, xB) {
  2121. return total + (xB > xA ? 0 : xB < xA ? 1 : 0.5);
  2122. }, 0);
  2123. }
  2124. function getU(sampleA, sampleB) {
  2125. return reduce(sampleA, function(total, xA) {
  2126. return total + getScore(xA, sampleB);
  2127. }, 0);
  2128. }
  2129. function getZ(u) {
  2130. return (u - ((size1 * size2) / 2)) / sqrt((size1 * size2 * (size1 + size2 + 1)) / 12);
  2131. }
  2132. // exit early if comparing the same benchmark
  2133. if (me == other) {
  2134. return 0;
  2135. }
  2136. // reject the null hyphothesis the two samples come from the
  2137. // same population (i.e. have the same median) if...
  2138. if (size1 + size2 > 30) {
  2139. // ...the z-stat is greater than 1.96 or less than -1.96
  2140. // http://www.statisticslectures.com/topics/mannwhitneyu/
  2141. zStat = getZ(u);
  2142. return abs(zStat) > 1.96 ? (zStat > 0 ? -1 : 1) : 0;
  2143. }
  2144. // ...the U value is less than or equal the critical U value
  2145. // http://www.geoib.com/mann-whitney-u-test.html
  2146. critical = maxSize < 5 || minSize < 3 ? 0 : uTable[maxSize][minSize - 3];
  2147. return u <= critical ? (u == u1 ? 1 : -1) : 0;
  2148. }
  2149. /**
  2150. * Reset properties and abort if running.
  2151. *
  2152. * @memberOf Benchmark
  2153. * @returns {Object} The benchmark instance.
  2154. */
  2155. function reset() {
  2156. var data,
  2157. event,
  2158. me = this,
  2159. index = 0,
  2160. changes = { 'length': 0 },
  2161. queue = { 'length': 0 };
  2162. if (me.running && !calledBy.abort) {
  2163. // no worries, `reset()` is called within `abort()`
  2164. calledBy.reset = true;
  2165. me.abort();
  2166. delete calledBy.reset;
  2167. }
  2168. else {
  2169. // a non-recursive solution to check if properties have changed
  2170. // http://www.jslab.dk/articles/non.recursive.preorder.traversal.part4
  2171. data = { 'destination': me, 'source': extend({}, me.constructor.prototype, me.options) };
  2172. do {
  2173. forOwn(data.source, function(value, key) {
  2174. var changed,
  2175. destination = data.destination,
  2176. currValue = destination[key];
  2177. if (value && typeof value == 'object') {
  2178. if (isClassOf(value, 'Array')) {
  2179. // check if an array value has changed to a non-array value
  2180. if (!isClassOf(currValue, 'Array')) {
  2181. changed = currValue = [];
  2182. }
  2183. // or has changed its length
  2184. if (currValue.length != value.length) {
  2185. changed = currValue = currValue.slice(0, value.length);
  2186. currValue.length = value.length;
  2187. }
  2188. }
  2189. // check if an object has changed to a non-object value
  2190. else if (!currValue || typeof currValue != 'object') {
  2191. changed = currValue = {};
  2192. }
  2193. // register a changed object
  2194. if (changed) {
  2195. changes[changes.length++] = { 'destination': destination, 'key': key, 'value': currValue };
  2196. }
  2197. queue[queue.length++] = { 'destination': currValue, 'source': value };
  2198. }
  2199. // register a changed primitive
  2200. else if (value !== currValue && !(value == null || isClassOf(value, 'Function'))) {
  2201. changes[changes.length++] = { 'destination': destination, 'key': key, 'value': value };
  2202. }
  2203. });
  2204. }
  2205. while ((data = queue[index++]));
  2206. // if changed emit the `reset` event and if it isn't cancelled reset the benchmark
  2207. if (changes.length && (me.emit(event = Event('reset')), !event.cancelled)) {
  2208. forEach(changes, function(data) {
  2209. data.destination[data.key] = data.value;
  2210. });
  2211. }
  2212. }
  2213. return me;
  2214. }
  2215. /**
  2216. * Displays relevant benchmark information when coerced to a string.
  2217. *
  2218. * @name toString
  2219. * @memberOf Benchmark
  2220. * @returns {String} A string representation of the benchmark instance.
  2221. */
  2222. function toStringBench() {
  2223. var me = this,
  2224. error = me.error,
  2225. hz = me.hz,
  2226. id = me.id,
  2227. stats = me.stats,
  2228. size = stats.sample.length,
  2229. pm = support.java ? '+/-' : '\xb1',
  2230. result = me.name || (isNaN(id) ? id : '<Test #' + id + '>');
  2231. if (error) {
  2232. result += ': ' + join(error);
  2233. } else {
  2234. result += ' x ' + formatNumber(hz.toFixed(hz < 100 ? 2 : 0)) + ' ops/sec ' + pm +
  2235. stats.rme.toFixed(2) + '% (' + size + ' run' + (size == 1 ? '' : 's') + ' sampled)';
  2236. }
  2237. return result;
  2238. }
  2239. /*--------------------------------------------------------------------------*/
  2240. /**
  2241. * Clocks the time taken to execute a test per cycle (secs).
  2242. *
  2243. * @private
  2244. * @param {Object} bench The benchmark instance.
  2245. * @returns {Number} The time taken.
  2246. */
  2247. function clock() {
  2248. var applet,
  2249. options = Benchmark.options,
  2250. template = { 'begin': 's$=new n$', 'end': 'r$=(new n$-s$)/1e3', 'uid': uid },
  2251. timers = [{ 'ns': timer.ns, 'res': max(0.0015, getRes('ms')), 'unit': 'ms' }];
  2252. // lazy define for hi-res timers
  2253. clock = function(clone) {
  2254. var deferred;
  2255. if (clone instanceof Deferred) {
  2256. deferred = clone;
  2257. clone = deferred.benchmark;
  2258. }
  2259. var bench = clone._original,
  2260. fn = bench.fn,
  2261. fnArg = deferred ? getFirstArgument(fn) || 'deferred' : '',
  2262. stringable = isStringable(fn);
  2263. var source = {
  2264. 'setup': getSource(bench.setup, preprocess('m$.setup()')),
  2265. 'fn': getSource(fn, preprocess('m$.fn(' + fnArg + ')')),
  2266. 'fnArg': fnArg,
  2267. 'teardown': getSource(bench.teardown, preprocess('m$.teardown()'))
  2268. };
  2269. var count = bench.count = clone.count,
  2270. decompilable = support.decompilation || stringable,
  2271. id = bench.id,
  2272. isEmpty = !(source.fn || stringable),
  2273. name = bench.name || (typeof id == 'number' ? '<Test #' + id + '>' : id),
  2274. ns = timer.ns,
  2275. result = 0;
  2276. // init `minTime` if needed
  2277. clone.minTime = bench.minTime || (bench.minTime = bench.options.minTime = options.minTime);
  2278. // repair nanosecond timer
  2279. // (some Chrome builds erase the `ns` variable after millions of executions)
  2280. if (applet) {
  2281. try {
  2282. ns.nanoTime();
  2283. } catch(e) {
  2284. // use non-element to avoid issues with libs that augment them
  2285. ns = timer.ns = new applet.Packages.nano;
  2286. }
  2287. }
  2288. // Compile in setup/teardown functions and the test loop.
  2289. // Create a new compiled test, instead of using the cached `bench.compiled`,
  2290. // to avoid potential engine optimizations enabled over the life of the test.
  2291. var compiled = bench.compiled = createFunction(preprocess('t$'), interpolate(
  2292. preprocess(deferred
  2293. ? 'var d$=this,#{fnArg}=d$,m$=d$.benchmark._original,f$=m$.fn,su$=m$.setup,td$=m$.teardown;' +
  2294. // when `deferred.cycles` is `0` then...
  2295. 'if(!d$.cycles){' +
  2296. // set `deferred.fn`
  2297. 'd$.fn=function(){var #{fnArg}=d$;if(typeof f$=="function"){try{#{fn}\n}catch(e$){f$(d$)}}else{#{fn}\n}};' +
  2298. // set `deferred.teardown`
  2299. 'd$.teardown=function(){d$.cycles=0;if(typeof td$=="function"){try{#{teardown}\n}catch(e$){td$()}}else{#{teardown}\n}};' +
  2300. // execute the benchmark's `setup`
  2301. 'if(typeof su$=="function"){try{#{setup}\n}catch(e$){su$()}}else{#{setup}\n};' +
  2302. // start timer
  2303. 't$.start(d$);' +
  2304. // execute `deferred.fn` and return a dummy object
  2305. '}d$.fn();return{}'
  2306. : 'var r$,s$,m$=this,f$=m$.fn,i$=m$.count,n$=t$.ns;#{setup}\n#{begin};' +
  2307. 'while(i$--){#{fn}\n}#{end};#{teardown}\nreturn{elapsed:r$,uid:"#{uid}"}'),
  2308. source
  2309. ));
  2310. try {
  2311. if (isEmpty) {
  2312. // Firefox may remove dead code from Function#toString results
  2313. // http://bugzil.la/536085
  2314. throw new Error('The test "' + name + '" is empty. This may be the result of dead code removal.');
  2315. }
  2316. else if (!deferred) {
  2317. // pretest to determine if compiled code is exits early, usually by a
  2318. // rogue `return` statement, by checking for a return object with the uid
  2319. bench.count = 1;
  2320. compiled = (compiled.call(bench, timer) || {}).uid == uid && compiled;
  2321. bench.count = count;
  2322. }
  2323. } catch(e) {
  2324. compiled = null;
  2325. clone.error = e || new Error(String(e));
  2326. bench.count = count;
  2327. }
  2328. // fallback when a test exits early or errors during pretest
  2329. if (decompilable && !compiled && !deferred && !isEmpty) {
  2330. compiled = createFunction(preprocess('t$'), interpolate(
  2331. preprocess(
  2332. (clone.error && !stringable
  2333. ? 'var r$,s$,m$=this,f$=m$.fn,i$=m$.count'
  2334. : 'function f$(){#{fn}\n}var r$,s$,m$=this,i$=m$.count'
  2335. ) +
  2336. ',n$=t$.ns;#{setup}\n#{begin};m$.f$=f$;while(i$--){m$.f$()}#{end};' +
  2337. 'delete m$.f$;#{teardown}\nreturn{elapsed:r$}'
  2338. ),
  2339. source
  2340. ));
  2341. try {
  2342. // pretest one more time to check for errors
  2343. bench.count = 1;
  2344. compiled.call(bench, timer);
  2345. bench.compiled = compiled;
  2346. bench.count = count;
  2347. delete clone.error;
  2348. }
  2349. catch(e) {
  2350. bench.count = count;
  2351. if (clone.error) {
  2352. compiled = null;
  2353. } else {
  2354. bench.compiled = compiled;
  2355. clone.error = e || new Error(String(e));
  2356. }
  2357. }
  2358. }
  2359. // assign `compiled` to `clone` before calling in case a deferred benchmark
  2360. // immediately calls `deferred.resolve()`
  2361. clone.compiled = compiled;
  2362. // if no errors run the full test loop
  2363. if (!clone.error) {
  2364. result = compiled.call(deferred || bench, timer).elapsed;
  2365. }
  2366. return result;
  2367. };
  2368. /*------------------------------------------------------------------------*/
  2369. /**
  2370. * Gets the current timer's minimum resolution (secs).
  2371. */
  2372. function getRes(unit) {
  2373. var measured,
  2374. begin,
  2375. count = 30,
  2376. divisor = 1e3,
  2377. ns = timer.ns,
  2378. sample = [];
  2379. // get average smallest measurable time
  2380. while (count--) {
  2381. if (unit == 'us') {
  2382. divisor = 1e6;
  2383. if (ns.stop) {
  2384. ns.start();
  2385. while (!(measured = ns.microseconds())) { }
  2386. } else if (ns[perfName]) {
  2387. divisor = 1e3;
  2388. measured = Function('n', 'var r,s=n.' + perfName + '();while(!(r=n.' + perfName + '()-s)){};return r')(ns);
  2389. } else {
  2390. begin = ns();
  2391. while (!(measured = ns() - begin)) { }
  2392. }
  2393. }
  2394. else if (unit == 'ns') {
  2395. divisor = 1e9;
  2396. if (ns.nanoTime) {
  2397. begin = ns.nanoTime();
  2398. while (!(measured = ns.nanoTime() - begin)) { }
  2399. } else {
  2400. begin = (begin = ns())[0] + (begin[1] / divisor);
  2401. while (!(measured = ((measured = ns())[0] + (measured[1] / divisor)) - begin)) { }
  2402. divisor = 1;
  2403. }
  2404. }
  2405. else {
  2406. begin = new ns;
  2407. while (!(measured = new ns - begin)) { }
  2408. }
  2409. // check for broken timers (nanoTime may have issues)
  2410. // http://alivebutsleepy.srnet.cz/unreliable-system-nanotime/
  2411. if (measured > 0) {
  2412. sample.push(measured);
  2413. } else {
  2414. sample.push(Infinity);
  2415. break;
  2416. }
  2417. }
  2418. // convert to seconds
  2419. return getMean(sample) / divisor;
  2420. }
  2421. /**
  2422. * Replaces all occurrences of `$` with a unique number and
  2423. * template tokens with content.
  2424. */
  2425. function preprocess(code) {
  2426. return interpolate(code, template).replace(/\$/g, /\d+/.exec(uid));
  2427. }
  2428. /*------------------------------------------------------------------------*/
  2429. // detect nanosecond support from a Java applet
  2430. each(doc && doc.applets || [], function(element) {
  2431. return !(timer.ns = applet = 'nanoTime' in element && element);
  2432. });
  2433. // check type in case Safari returns an object instead of a number
  2434. try {
  2435. if (typeof timer.ns.nanoTime() == 'number') {
  2436. timers.push({ 'ns': timer.ns, 'res': getRes('ns'), 'unit': 'ns' });
  2437. }
  2438. } catch(e) { }
  2439. // detect Chrome's microsecond timer:
  2440. // enable benchmarking via the --enable-benchmarking command
  2441. // line switch in at least Chrome 7 to use chrome.Interval
  2442. try {
  2443. if ((timer.ns = new (window.chrome || window.chromium).Interval)) {
  2444. timers.push({ 'ns': timer.ns, 'res': getRes('us'), 'unit': 'us' });
  2445. }
  2446. } catch(e) { }
  2447. // detect `performance.now` microsecond resolution timer
  2448. if ((timer.ns = perfName && perfObject)) {
  2449. timers.push({ 'ns': timer.ns, 'res': getRes('us'), 'unit': 'us' });
  2450. }
  2451. // detect Node's nanosecond resolution timer available in Node >= 0.8
  2452. if (processObject && typeof (timer.ns = processObject.hrtime) == 'function') {
  2453. timers.push({ 'ns': timer.ns, 'res': getRes('ns'), 'unit': 'ns' });
  2454. }
  2455. // detect Wade Simmons' Node microtime module
  2456. if (microtimeObject && typeof (timer.ns = microtimeObject.now) == 'function') {
  2457. timers.push({ 'ns': timer.ns, 'res': getRes('us'), 'unit': 'us' });
  2458. }
  2459. // pick timer with highest resolution
  2460. timer = reduce(timers, function(timer, other) {
  2461. return other.res < timer.res ? other : timer;
  2462. });
  2463. // remove unused applet
  2464. if (timer.unit != 'ns' && applet) {
  2465. applet = destroyElement(applet);
  2466. }
  2467. // error if there are no working timers
  2468. if (timer.res == Infinity) {
  2469. throw new Error('Benchmark.js was unable to find a working timer.');
  2470. }
  2471. // use API of chosen timer
  2472. if (timer.unit == 'ns') {
  2473. if (timer.ns.nanoTime) {
  2474. extend(template, {
  2475. 'begin': 's$=n$.nanoTime()',
  2476. 'end': 'r$=(n$.nanoTime()-s$)/1e9'
  2477. });
  2478. } else {
  2479. extend(template, {
  2480. 'begin': 's$=n$()',
  2481. 'end': 'r$=n$(s$);r$=r$[0]+(r$[1]/1e9)'
  2482. });
  2483. }
  2484. }
  2485. else if (timer.unit == 'us') {
  2486. if (timer.ns.stop) {
  2487. extend(template, {
  2488. 'begin': 's$=n$.start()',
  2489. 'end': 'r$=n$.microseconds()/1e6'
  2490. });
  2491. } else if (perfName) {
  2492. extend(template, {
  2493. 'begin': 's$=n$.' + perfName + '()',
  2494. 'end': 'r$=(n$.' + perfName + '()-s$)/1e3'
  2495. });
  2496. } else {
  2497. extend(template, {
  2498. 'begin': 's$=n$()',
  2499. 'end': 'r$=(n$()-s$)/1e6'
  2500. });
  2501. }
  2502. }
  2503. // define `timer` methods
  2504. timer.start = createFunction(preprocess('o$'),
  2505. preprocess('var n$=this.ns,#{begin};o$.elapsed=0;o$.timeStamp=s$'));
  2506. timer.stop = createFunction(preprocess('o$'),
  2507. preprocess('var n$=this.ns,s$=o$.timeStamp,#{end};o$.elapsed=r$'));
  2508. // resolve time span required to achieve a percent uncertainty of at most 1%
  2509. // http://spiff.rit.edu/classes/phys273/uncert/uncert.html
  2510. options.minTime || (options.minTime = max(timer.res / 2 / 0.01, 0.05));
  2511. return clock.apply(null, arguments);
  2512. }
  2513. /*--------------------------------------------------------------------------*/
  2514. /**
  2515. * Computes stats on benchmark results.
  2516. *
  2517. * @private
  2518. * @param {Object} bench The benchmark instance.
  2519. * @param {Object} options The options object.
  2520. */
  2521. function compute(bench, options) {
  2522. options || (options = {});
  2523. var async = options.async,
  2524. elapsed = 0,
  2525. initCount = bench.initCount,
  2526. minSamples = bench.minSamples,
  2527. queue = [],
  2528. sample = bench.stats.sample;
  2529. /**
  2530. * Adds a clone to the queue.
  2531. */
  2532. function enqueue() {
  2533. queue.push(bench.clone({
  2534. '_original': bench,
  2535. 'events': {
  2536. 'abort': [update],
  2537. 'cycle': [update],
  2538. 'error': [update],
  2539. 'start': [update]
  2540. }
  2541. }));
  2542. }
  2543. /**
  2544. * Updates the clone/original benchmarks to keep their data in sync.
  2545. */
  2546. function update(event) {
  2547. var clone = this,
  2548. type = event.type;
  2549. if (bench.running) {
  2550. if (type == 'start') {
  2551. // Note: `clone.minTime` prop is inited in `clock()`
  2552. clone.count = bench.initCount;
  2553. }
  2554. else {
  2555. if (type == 'error') {
  2556. bench.error = clone.error;
  2557. }
  2558. if (type == 'abort') {
  2559. bench.abort();
  2560. bench.emit('cycle');
  2561. } else {
  2562. event.currentTarget = event.target = bench;
  2563. bench.emit(event);
  2564. }
  2565. }
  2566. } else if (bench.aborted) {
  2567. // clear abort listeners to avoid triggering bench's abort/cycle again
  2568. clone.events.abort.length = 0;
  2569. clone.abort();
  2570. }
  2571. }
  2572. /**
  2573. * Determines if more clones should be queued or if cycling should stop.
  2574. */
  2575. function evaluate(event) {
  2576. var critical,
  2577. df,
  2578. mean,
  2579. moe,
  2580. rme,
  2581. sd,
  2582. sem,
  2583. variance,
  2584. clone = event.target,
  2585. done = bench.aborted,
  2586. now = +new Date,
  2587. size = sample.push(clone.times.period),
  2588. maxedOut = size >= minSamples && (elapsed += now - clone.times.timeStamp) / 1e3 > bench.maxTime,
  2589. times = bench.times,
  2590. varOf = function(sum, x) { return sum + pow(x - mean, 2); };
  2591. // exit early for aborted or unclockable tests
  2592. if (done || clone.hz == Infinity) {
  2593. maxedOut = !(size = sample.length = queue.length = 0);
  2594. }
  2595. if (!done) {
  2596. // sample mean (estimate of the population mean)
  2597. mean = getMean(sample);
  2598. // sample variance (estimate of the population variance)
  2599. variance = reduce(sample, varOf, 0) / (size - 1) || 0;
  2600. // sample standard deviation (estimate of the population standard deviation)
  2601. sd = sqrt(variance);
  2602. // standard error of the mean (a.k.a. the standard deviation of the sampling distribution of the sample mean)
  2603. sem = sd / sqrt(size);
  2604. // degrees of freedom
  2605. df = size - 1;
  2606. // critical value
  2607. critical = tTable[Math.round(df) || 1] || tTable.infinity;
  2608. // margin of error
  2609. moe = sem * critical;
  2610. // relative margin of error
  2611. rme = (moe / mean) * 100 || 0;
  2612. extend(bench.stats, {
  2613. 'deviation': sd,
  2614. 'mean': mean,
  2615. 'moe': moe,
  2616. 'rme': rme,
  2617. 'sem': sem,
  2618. 'variance': variance
  2619. });
  2620. // Abort the cycle loop when the minimum sample size has been collected
  2621. // and the elapsed time exceeds the maximum time allowed per benchmark.
  2622. // We don't count cycle delays toward the max time because delays may be
  2623. // increased by browsers that clamp timeouts for inactive tabs.
  2624. // https://developer.mozilla.org/en/window.setTimeout#Inactive_tabs
  2625. if (maxedOut) {
  2626. // reset the `initCount` in case the benchmark is rerun
  2627. bench.initCount = initCount;
  2628. bench.running = false;
  2629. done = true;
  2630. times.elapsed = (now - times.timeStamp) / 1e3;
  2631. }
  2632. if (bench.hz != Infinity) {
  2633. bench.hz = 1 / mean;
  2634. times.cycle = mean * bench.count;
  2635. times.period = mean;
  2636. }
  2637. }
  2638. // if time permits, increase sample size to reduce the margin of error
  2639. if (queue.length < 2 && !maxedOut) {
  2640. enqueue();
  2641. }
  2642. // abort the invoke cycle when done
  2643. event.aborted = done;
  2644. }
  2645. // init queue and begin
  2646. enqueue();
  2647. invoke(queue, {
  2648. 'name': 'run',
  2649. 'args': { 'async': async },
  2650. 'queued': true,
  2651. 'onCycle': evaluate,
  2652. 'onComplete': function() { bench.emit('complete'); }
  2653. });
  2654. }
  2655. /*--------------------------------------------------------------------------*/
  2656. /**
  2657. * Cycles a benchmark until a run `count` can be established.
  2658. *
  2659. * @private
  2660. * @param {Object} clone The cloned benchmark instance.
  2661. * @param {Object} options The options object.
  2662. */
  2663. function cycle(clone, options) {
  2664. options || (options = {});
  2665. var deferred;
  2666. if (clone instanceof Deferred) {
  2667. deferred = clone;
  2668. clone = clone.benchmark;
  2669. }
  2670. var clocked,
  2671. cycles,
  2672. divisor,
  2673. event,
  2674. minTime,
  2675. period,
  2676. async = options.async,
  2677. bench = clone._original,
  2678. count = clone.count,
  2679. times = clone.times;
  2680. // continue, if not aborted between cycles
  2681. if (clone.running) {
  2682. // `minTime` is set to `Benchmark.options.minTime` in `clock()`
  2683. cycles = ++clone.cycles;
  2684. clocked = deferred ? deferred.elapsed : clock(clone);
  2685. minTime = clone.minTime;
  2686. if (cycles > bench.cycles) {
  2687. bench.cycles = cycles;
  2688. }
  2689. if (clone.error) {
  2690. event = Event('error');
  2691. event.message = clone.error;
  2692. clone.emit(event);
  2693. if (!event.cancelled) {
  2694. clone.abort();
  2695. }
  2696. }
  2697. }
  2698. // continue, if not errored
  2699. if (clone.running) {
  2700. // time taken to complete last test cycle
  2701. bench.times.cycle = times.cycle = clocked;
  2702. // seconds per operation
  2703. period = bench.times.period = times.period = clocked / count;
  2704. // ops per second
  2705. bench.hz = clone.hz = 1 / period;
  2706. // avoid working our way up to this next time
  2707. bench.initCount = clone.initCount = count;
  2708. // do we need to do another cycle?
  2709. clone.running = clocked < minTime;
  2710. if (clone.running) {
  2711. // tests may clock at `0` when `initCount` is a small number,
  2712. // to avoid that we set its count to something a bit higher
  2713. if (!clocked && (divisor = divisors[clone.cycles]) != null) {
  2714. count = floor(4e6 / divisor);
  2715. }
  2716. // calculate how many more iterations it will take to achive the `minTime`
  2717. if (count <= clone.count) {
  2718. count += Math.ceil((minTime - clocked) / period);
  2719. }
  2720. clone.running = count != Infinity;
  2721. }
  2722. }
  2723. // should we exit early?
  2724. event = Event('cycle');
  2725. clone.emit(event);
  2726. if (event.aborted) {
  2727. clone.abort();
  2728. }
  2729. // figure out what to do next
  2730. if (clone.running) {
  2731. // start a new cycle
  2732. clone.count = count;
  2733. if (deferred) {
  2734. clone.compiled.call(deferred, timer);
  2735. } else if (async) {
  2736. delay(clone, function() { cycle(clone, options); });
  2737. } else {
  2738. cycle(clone);
  2739. }
  2740. }
  2741. else {
  2742. // fix TraceMonkey bug associated with clock fallbacks
  2743. // http://bugzil.la/509069
  2744. if (support.browser) {
  2745. runScript(uid + '=1;delete ' + uid);
  2746. }
  2747. // done
  2748. clone.emit('complete');
  2749. }
  2750. }
  2751. /*--------------------------------------------------------------------------*/
  2752. /**
  2753. * Runs the benchmark.
  2754. *
  2755. * @memberOf Benchmark
  2756. * @param {Object} [options={}] Options object.
  2757. * @returns {Object} The benchmark instance.
  2758. * @example
  2759. *
  2760. * // basic usage
  2761. * bench.run();
  2762. *
  2763. * // or with options
  2764. * bench.run({ 'async': true });
  2765. */
  2766. function run(options) {
  2767. var me = this,
  2768. event = Event('start');
  2769. // set `running` to `false` so `reset()` won't call `abort()`
  2770. me.running = false;
  2771. me.reset();
  2772. me.running = true;
  2773. me.count = me.initCount;
  2774. me.times.timeStamp = +new Date;
  2775. me.emit(event);
  2776. if (!event.cancelled) {
  2777. options = { 'async': ((options = options && options.async) == null ? me.async : options) && support.timeout };
  2778. // for clones created within `compute()`
  2779. if (me._original) {
  2780. if (me.defer) {
  2781. Deferred(me);
  2782. } else {
  2783. cycle(me, options);
  2784. }
  2785. }
  2786. // for original benchmarks
  2787. else {
  2788. compute(me, options);
  2789. }
  2790. }
  2791. return me;
  2792. }
  2793. /*--------------------------------------------------------------------------*/
  2794. // Firefox 1 erroneously defines variable and argument names of functions on
  2795. // the function itself as non-configurable properties with `undefined` values.
  2796. // The bugginess continues as the `Benchmark` constructor has an argument
  2797. // named `options` and Firefox 1 will not assign a value to `Benchmark.options`,
  2798. // making it non-writable in the process, unless it is the first property
  2799. // assigned by for-in loop of `extend()`.
  2800. extend(Benchmark, {
  2801. /**
  2802. * The default options copied by benchmark instances.
  2803. *
  2804. * @static
  2805. * @memberOf Benchmark
  2806. * @type Object
  2807. */
  2808. 'options': {
  2809. /**
  2810. * A flag to indicate that benchmark cycles will execute asynchronously
  2811. * by default.
  2812. *
  2813. * @memberOf Benchmark.options
  2814. * @type Boolean
  2815. */
  2816. 'async': false,
  2817. /**
  2818. * A flag to indicate that the benchmark clock is deferred.
  2819. *
  2820. * @memberOf Benchmark.options
  2821. * @type Boolean
  2822. */
  2823. 'defer': false,
  2824. /**
  2825. * The delay between test cycles (secs).
  2826. * @memberOf Benchmark.options
  2827. * @type Number
  2828. */
  2829. 'delay': 0.005,
  2830. /**
  2831. * Displayed by Benchmark#toString when a `name` is not available
  2832. * (auto-generated if absent).
  2833. *
  2834. * @memberOf Benchmark.options
  2835. * @type String
  2836. */
  2837. 'id': undefined,
  2838. /**
  2839. * The default number of times to execute a test on a benchmark's first cycle.
  2840. *
  2841. * @memberOf Benchmark.options
  2842. * @type Number
  2843. */
  2844. 'initCount': 1,
  2845. /**
  2846. * The maximum time a benchmark is allowed to run before finishing (secs).
  2847. * Note: Cycle delays aren't counted toward the maximum time.
  2848. *
  2849. * @memberOf Benchmark.options
  2850. * @type Number
  2851. */
  2852. 'maxTime': 5,
  2853. /**
  2854. * The minimum sample size required to perform statistical analysis.
  2855. *
  2856. * @memberOf Benchmark.options
  2857. * @type Number
  2858. */
  2859. 'minSamples': 5,
  2860. /**
  2861. * The time needed to reduce the percent uncertainty of measurement to 1% (secs).
  2862. *
  2863. * @memberOf Benchmark.options
  2864. * @type Number
  2865. */
  2866. 'minTime': 0,
  2867. /**
  2868. * The name of the benchmark.
  2869. *
  2870. * @memberOf Benchmark.options
  2871. * @type String
  2872. */
  2873. 'name': undefined,
  2874. /**
  2875. * An event listener called when the benchmark is aborted.
  2876. *
  2877. * @memberOf Benchmark.options
  2878. * @type Function
  2879. */
  2880. 'onAbort': undefined,
  2881. /**
  2882. * An event listener called when the benchmark completes running.
  2883. *
  2884. * @memberOf Benchmark.options
  2885. * @type Function
  2886. */
  2887. 'onComplete': undefined,
  2888. /**
  2889. * An event listener called after each run cycle.
  2890. *
  2891. * @memberOf Benchmark.options
  2892. * @type Function
  2893. */
  2894. 'onCycle': undefined,
  2895. /**
  2896. * An event listener called when a test errors.
  2897. *
  2898. * @memberOf Benchmark.options
  2899. * @type Function
  2900. */
  2901. 'onError': undefined,
  2902. /**
  2903. * An event listener called when the benchmark is reset.
  2904. *
  2905. * @memberOf Benchmark.options
  2906. * @type Function
  2907. */
  2908. 'onReset': undefined,
  2909. /**
  2910. * An event listener called when the benchmark starts running.
  2911. *
  2912. * @memberOf Benchmark.options
  2913. * @type Function
  2914. */
  2915. 'onStart': undefined
  2916. },
  2917. /**
  2918. * Platform object with properties describing things like browser name,
  2919. * version, and operating system.
  2920. *
  2921. * @static
  2922. * @memberOf Benchmark
  2923. * @type Object
  2924. */
  2925. 'platform': req('platform') || window.platform || {
  2926. /**
  2927. * The platform description.
  2928. *
  2929. * @memberOf Benchmark.platform
  2930. * @type String
  2931. */
  2932. 'description': window.navigator && navigator.userAgent || null,
  2933. /**
  2934. * The name of the browser layout engine.
  2935. *
  2936. * @memberOf Benchmark.platform
  2937. * @type String|Null
  2938. */
  2939. 'layout': null,
  2940. /**
  2941. * The name of the product hosting the browser.
  2942. *
  2943. * @memberOf Benchmark.platform
  2944. * @type String|Null
  2945. */
  2946. 'product': null,
  2947. /**
  2948. * The name of the browser/environment.
  2949. *
  2950. * @memberOf Benchmark.platform
  2951. * @type String|Null
  2952. */
  2953. 'name': null,
  2954. /**
  2955. * The name of the product's manufacturer.
  2956. *
  2957. * @memberOf Benchmark.platform
  2958. * @type String|Null
  2959. */
  2960. 'manufacturer': null,
  2961. /**
  2962. * The name of the operating system.
  2963. *
  2964. * @memberOf Benchmark.platform
  2965. * @type String|Null
  2966. */
  2967. 'os': null,
  2968. /**
  2969. * The alpha/beta release indicator.
  2970. *
  2971. * @memberOf Benchmark.platform
  2972. * @type String|Null
  2973. */
  2974. 'prerelease': null,
  2975. /**
  2976. * The browser/environment version.
  2977. *
  2978. * @memberOf Benchmark.platform
  2979. * @type String|Null
  2980. */
  2981. 'version': null,
  2982. /**
  2983. * Return platform description when the platform object is coerced to a string.
  2984. *
  2985. * @memberOf Benchmark.platform
  2986. * @type Function
  2987. * @returns {String} The platform description.
  2988. */
  2989. 'toString': function() {
  2990. return this.description || '';
  2991. }
  2992. },
  2993. /**
  2994. * The semantic version number.
  2995. *
  2996. * @static
  2997. * @memberOf Benchmark
  2998. * @type String
  2999. */
  3000. 'version': '1.0.0',
  3001. // an object of environment/feature detection flags
  3002. 'support': support,
  3003. // clone objects
  3004. 'deepClone': deepClone,
  3005. // iteration utility
  3006. 'each': each,
  3007. // augment objects
  3008. 'extend': extend,
  3009. // generic Array#filter
  3010. 'filter': filter,
  3011. // generic Array#forEach
  3012. 'forEach': forEach,
  3013. // generic own property iteration utility
  3014. 'forOwn': forOwn,
  3015. // converts a number to a comma-separated string
  3016. 'formatNumber': formatNumber,
  3017. // generic Object#hasOwnProperty
  3018. // (trigger hasKey's lazy define before assigning it to Benchmark)
  3019. 'hasKey': (hasKey(Benchmark, ''), hasKey),
  3020. // generic Array#indexOf
  3021. 'indexOf': indexOf,
  3022. // template utility
  3023. 'interpolate': interpolate,
  3024. // invokes a method on each item in an array
  3025. 'invoke': invoke,
  3026. // generic Array#join for arrays and objects
  3027. 'join': join,
  3028. // generic Array#map
  3029. 'map': map,
  3030. // retrieves a property value from each item in an array
  3031. 'pluck': pluck,
  3032. // generic Array#reduce
  3033. 'reduce': reduce
  3034. });
  3035. /*--------------------------------------------------------------------------*/
  3036. extend(Benchmark.prototype, {
  3037. /**
  3038. * The number of times a test was executed.
  3039. *
  3040. * @memberOf Benchmark
  3041. * @type Number
  3042. */
  3043. 'count': 0,
  3044. /**
  3045. * The number of cycles performed while benchmarking.
  3046. *
  3047. * @memberOf Benchmark
  3048. * @type Number
  3049. */
  3050. 'cycles': 0,
  3051. /**
  3052. * The number of executions per second.
  3053. *
  3054. * @memberOf Benchmark
  3055. * @type Number
  3056. */
  3057. 'hz': 0,
  3058. /**
  3059. * The compiled test function.
  3060. *
  3061. * @memberOf Benchmark
  3062. * @type Function|String
  3063. */
  3064. 'compiled': undefined,
  3065. /**
  3066. * The error object if the test failed.
  3067. *
  3068. * @memberOf Benchmark
  3069. * @type Object
  3070. */
  3071. 'error': undefined,
  3072. /**
  3073. * The test to benchmark.
  3074. *
  3075. * @memberOf Benchmark
  3076. * @type Function|String
  3077. */
  3078. 'fn': undefined,
  3079. /**
  3080. * A flag to indicate if the benchmark is aborted.
  3081. *
  3082. * @memberOf Benchmark
  3083. * @type Boolean
  3084. */
  3085. 'aborted': false,
  3086. /**
  3087. * A flag to indicate if the benchmark is running.
  3088. *
  3089. * @memberOf Benchmark
  3090. * @type Boolean
  3091. */
  3092. 'running': false,
  3093. /**
  3094. * Compiled into the test and executed immediately **before** the test loop.
  3095. *
  3096. * @memberOf Benchmark
  3097. * @type Function|String
  3098. * @example
  3099. *
  3100. * // basic usage
  3101. * var bench = Benchmark({
  3102. * 'setup': function() {
  3103. * var c = this.count,
  3104. * element = document.getElementById('container');
  3105. * while (c--) {
  3106. * element.appendChild(document.createElement('div'));
  3107. * }
  3108. * },
  3109. * 'fn': function() {
  3110. * element.removeChild(element.lastChild);
  3111. * }
  3112. * });
  3113. *
  3114. * // compiles to something like:
  3115. * var c = this.count,
  3116. * element = document.getElementById('container');
  3117. * while (c--) {
  3118. * element.appendChild(document.createElement('div'));
  3119. * }
  3120. * var start = new Date;
  3121. * while (count--) {
  3122. * element.removeChild(element.lastChild);
  3123. * }
  3124. * var end = new Date - start;
  3125. *
  3126. * // or using strings
  3127. * var bench = Benchmark({
  3128. * 'setup': '\
  3129. * var a = 0;\n\
  3130. * (function() {\n\
  3131. * (function() {\n\
  3132. * (function() {',
  3133. * 'fn': 'a += 1;',
  3134. * 'teardown': '\
  3135. * }())\n\
  3136. * }())\n\
  3137. * }())'
  3138. * });
  3139. *
  3140. * // compiles to something like:
  3141. * var a = 0;
  3142. * (function() {
  3143. * (function() {
  3144. * (function() {
  3145. * var start = new Date;
  3146. * while (count--) {
  3147. * a += 1;
  3148. * }
  3149. * var end = new Date - start;
  3150. * }())
  3151. * }())
  3152. * }())
  3153. */
  3154. 'setup': noop,
  3155. /**
  3156. * Compiled into the test and executed immediately **after** the test loop.
  3157. *
  3158. * @memberOf Benchmark
  3159. * @type Function|String
  3160. */
  3161. 'teardown': noop,
  3162. /**
  3163. * An object of stats including mean, margin or error, and standard deviation.
  3164. *
  3165. * @memberOf Benchmark
  3166. * @type Object
  3167. */
  3168. 'stats': {
  3169. /**
  3170. * The margin of error.
  3171. *
  3172. * @memberOf Benchmark#stats
  3173. * @type Number
  3174. */
  3175. 'moe': 0,
  3176. /**
  3177. * The relative margin of error (expressed as a percentage of the mean).
  3178. *
  3179. * @memberOf Benchmark#stats
  3180. * @type Number
  3181. */
  3182. 'rme': 0,
  3183. /**
  3184. * The standard error of the mean.
  3185. *
  3186. * @memberOf Benchmark#stats
  3187. * @type Number
  3188. */
  3189. 'sem': 0,
  3190. /**
  3191. * The sample standard deviation.
  3192. *
  3193. * @memberOf Benchmark#stats
  3194. * @type Number
  3195. */
  3196. 'deviation': 0,
  3197. /**
  3198. * The sample arithmetic mean.
  3199. *
  3200. * @memberOf Benchmark#stats
  3201. * @type Number
  3202. */
  3203. 'mean': 0,
  3204. /**
  3205. * The array of sampled periods.
  3206. *
  3207. * @memberOf Benchmark#stats
  3208. * @type Array
  3209. */
  3210. 'sample': [],
  3211. /**
  3212. * The sample variance.
  3213. *
  3214. * @memberOf Benchmark#stats
  3215. * @type Number
  3216. */
  3217. 'variance': 0
  3218. },
  3219. /**
  3220. * An object of timing data including cycle, elapsed, period, start, and stop.
  3221. *
  3222. * @memberOf Benchmark
  3223. * @type Object
  3224. */
  3225. 'times': {
  3226. /**
  3227. * The time taken to complete the last cycle (secs).
  3228. *
  3229. * @memberOf Benchmark#times
  3230. * @type Number
  3231. */
  3232. 'cycle': 0,
  3233. /**
  3234. * The time taken to complete the benchmark (secs).
  3235. *
  3236. * @memberOf Benchmark#times
  3237. * @type Number
  3238. */
  3239. 'elapsed': 0,
  3240. /**
  3241. * The time taken to execute the test once (secs).
  3242. *
  3243. * @memberOf Benchmark#times
  3244. * @type Number
  3245. */
  3246. 'period': 0,
  3247. /**
  3248. * A timestamp of when the benchmark started (ms).
  3249. *
  3250. * @memberOf Benchmark#times
  3251. * @type Number
  3252. */
  3253. 'timeStamp': 0
  3254. },
  3255. // aborts benchmark (does not record times)
  3256. 'abort': abort,
  3257. // creates a new benchmark using the same test and options
  3258. 'clone': clone,
  3259. // compares benchmark's hertz with another
  3260. 'compare': compare,
  3261. // executes listeners
  3262. 'emit': emit,
  3263. // get listeners
  3264. 'listeners': listeners,
  3265. // unregister listeners
  3266. 'off': off,
  3267. // register listeners
  3268. 'on': on,
  3269. // reset benchmark properties
  3270. 'reset': reset,
  3271. // runs the benchmark
  3272. 'run': run,
  3273. // pretty print benchmark info
  3274. 'toString': toStringBench
  3275. });
  3276. /*--------------------------------------------------------------------------*/
  3277. extend(Deferred.prototype, {
  3278. /**
  3279. * The deferred benchmark instance.
  3280. *
  3281. * @memberOf Benchmark.Deferred
  3282. * @type Object
  3283. */
  3284. 'benchmark': null,
  3285. /**
  3286. * The number of deferred cycles performed while benchmarking.
  3287. *
  3288. * @memberOf Benchmark.Deferred
  3289. * @type Number
  3290. */
  3291. 'cycles': 0,
  3292. /**
  3293. * The time taken to complete the deferred benchmark (secs).
  3294. *
  3295. * @memberOf Benchmark.Deferred
  3296. * @type Number
  3297. */
  3298. 'elapsed': 0,
  3299. /**
  3300. * A timestamp of when the deferred benchmark started (ms).
  3301. *
  3302. * @memberOf Benchmark.Deferred
  3303. * @type Number
  3304. */
  3305. 'timeStamp': 0,
  3306. // cycles/completes the deferred benchmark
  3307. 'resolve': resolve
  3308. });
  3309. /*--------------------------------------------------------------------------*/
  3310. extend(Event.prototype, {
  3311. /**
  3312. * A flag to indicate if the emitters listener iteration is aborted.
  3313. *
  3314. * @memberOf Benchmark.Event
  3315. * @type Boolean
  3316. */
  3317. 'aborted': false,
  3318. /**
  3319. * A flag to indicate if the default action is cancelled.
  3320. *
  3321. * @memberOf Benchmark.Event
  3322. * @type Boolean
  3323. */
  3324. 'cancelled': false,
  3325. /**
  3326. * The object whose listeners are currently being processed.
  3327. *
  3328. * @memberOf Benchmark.Event
  3329. * @type Object
  3330. */
  3331. 'currentTarget': undefined,
  3332. /**
  3333. * The return value of the last executed listener.
  3334. *
  3335. * @memberOf Benchmark.Event
  3336. * @type Mixed
  3337. */
  3338. 'result': undefined,
  3339. /**
  3340. * The object to which the event was originally emitted.
  3341. *
  3342. * @memberOf Benchmark.Event
  3343. * @type Object
  3344. */
  3345. 'target': undefined,
  3346. /**
  3347. * A timestamp of when the event was created (ms).
  3348. *
  3349. * @memberOf Benchmark.Event
  3350. * @type Number
  3351. */
  3352. 'timeStamp': 0,
  3353. /**
  3354. * The event type.
  3355. *
  3356. * @memberOf Benchmark.Event
  3357. * @type String
  3358. */
  3359. 'type': ''
  3360. });
  3361. /*--------------------------------------------------------------------------*/
  3362. /**
  3363. * The default options copied by suite instances.
  3364. *
  3365. * @static
  3366. * @memberOf Benchmark.Suite
  3367. * @type Object
  3368. */
  3369. Suite.options = {
  3370. /**
  3371. * The name of the suite.
  3372. *
  3373. * @memberOf Benchmark.Suite.options
  3374. * @type String
  3375. */
  3376. 'name': undefined
  3377. };
  3378. /*--------------------------------------------------------------------------*/
  3379. extend(Suite.prototype, {
  3380. /**
  3381. * The number of benchmarks in the suite.
  3382. *
  3383. * @memberOf Benchmark.Suite
  3384. * @type Number
  3385. */
  3386. 'length': 0,
  3387. /**
  3388. * A flag to indicate if the suite is aborted.
  3389. *
  3390. * @memberOf Benchmark.Suite
  3391. * @type Boolean
  3392. */
  3393. 'aborted': false,
  3394. /**
  3395. * A flag to indicate if the suite is running.
  3396. *
  3397. * @memberOf Benchmark.Suite
  3398. * @type Boolean
  3399. */
  3400. 'running': false,
  3401. /**
  3402. * An `Array#forEach` like method.
  3403. * Callbacks may terminate the loop by explicitly returning `false`.
  3404. *
  3405. * @memberOf Benchmark.Suite
  3406. * @param {Function} callback The function called per iteration.
  3407. * @returns {Object} The suite iterated over.
  3408. */
  3409. 'forEach': methodize(forEach),
  3410. /**
  3411. * An `Array#indexOf` like method.
  3412. *
  3413. * @memberOf Benchmark.Suite
  3414. * @param {Mixed} value The value to search for.
  3415. * @returns {Number} The index of the matched value or `-1`.
  3416. */
  3417. 'indexOf': methodize(indexOf),
  3418. /**
  3419. * Invokes a method on all benchmarks in the suite.
  3420. *
  3421. * @memberOf Benchmark.Suite
  3422. * @param {String|Object} name The name of the method to invoke OR options object.
  3423. * @param {Mixed} [arg1, arg2, ...] Arguments to invoke the method with.
  3424. * @returns {Array} A new array of values returned from each method invoked.
  3425. */
  3426. 'invoke': methodize(invoke),
  3427. /**
  3428. * Converts the suite of benchmarks to a string.
  3429. *
  3430. * @memberOf Benchmark.Suite
  3431. * @param {String} [separator=','] A string to separate each element of the array.
  3432. * @returns {String} The string.
  3433. */
  3434. 'join': [].join,
  3435. /**
  3436. * An `Array#map` like method.
  3437. *
  3438. * @memberOf Benchmark.Suite
  3439. * @param {Function} callback The function called per iteration.
  3440. * @returns {Array} A new array of values returned by the callback.
  3441. */
  3442. 'map': methodize(map),
  3443. /**
  3444. * Retrieves the value of a specified property from all benchmarks in the suite.
  3445. *
  3446. * @memberOf Benchmark.Suite
  3447. * @param {String} property The property to pluck.
  3448. * @returns {Array} A new array of property values.
  3449. */
  3450. 'pluck': methodize(pluck),
  3451. /**
  3452. * Removes the last benchmark from the suite and returns it.
  3453. *
  3454. * @memberOf Benchmark.Suite
  3455. * @returns {Mixed} The removed benchmark.
  3456. */
  3457. 'pop': [].pop,
  3458. /**
  3459. * Appends benchmarks to the suite.
  3460. *
  3461. * @memberOf Benchmark.Suite
  3462. * @returns {Number} The suite's new length.
  3463. */
  3464. 'push': [].push,
  3465. /**
  3466. * Sorts the benchmarks of the suite.
  3467. *
  3468. * @memberOf Benchmark.Suite
  3469. * @param {Function} [compareFn=null] A function that defines the sort order.
  3470. * @returns {Object} The sorted suite.
  3471. */
  3472. 'sort': [].sort,
  3473. /**
  3474. * An `Array#reduce` like method.
  3475. *
  3476. * @memberOf Benchmark.Suite
  3477. * @param {Function} callback The function called per iteration.
  3478. * @param {Mixed} accumulator Initial value of the accumulator.
  3479. * @returns {Mixed} The accumulator.
  3480. */
  3481. 'reduce': methodize(reduce),
  3482. // aborts all benchmarks in the suite
  3483. 'abort': abortSuite,
  3484. // adds a benchmark to the suite
  3485. 'add': add,
  3486. // creates a new suite with cloned benchmarks
  3487. 'clone': cloneSuite,
  3488. // executes listeners of a specified type
  3489. 'emit': emit,
  3490. // creates a new suite of filtered benchmarks
  3491. 'filter': filterSuite,
  3492. // get listeners
  3493. 'listeners': listeners,
  3494. // unregister listeners
  3495. 'off': off,
  3496. // register listeners
  3497. 'on': on,
  3498. // resets all benchmarks in the suite
  3499. 'reset': resetSuite,
  3500. // runs all benchmarks in the suite
  3501. 'run': runSuite,
  3502. // array methods
  3503. 'concat': concat,
  3504. 'reverse': reverse,
  3505. 'shift': shift,
  3506. 'slice': slice,
  3507. 'splice': splice,
  3508. 'unshift': unshift
  3509. });
  3510. /*--------------------------------------------------------------------------*/
  3511. // expose Deferred, Event and Suite
  3512. extend(Benchmark, {
  3513. 'Deferred': Deferred,
  3514. 'Event': Event,
  3515. 'Suite': Suite
  3516. });
  3517. // expose Benchmark
  3518. // some AMD build optimizers, like r.js, check for specific condition patterns like the following:
  3519. if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
  3520. // define as an anonymous module so, through path mapping, it can be aliased
  3521. define(function() {
  3522. return Benchmark;
  3523. });
  3524. }
  3525. // check for `exports` after `define` in case a build optimizer adds an `exports` object
  3526. else if (freeExports) {
  3527. // in Node.js or RingoJS v0.8.0+
  3528. if (typeof module == 'object' && module && module.exports == freeExports) {
  3529. (module.exports = Benchmark).Benchmark = Benchmark;
  3530. }
  3531. // in Narwhal or RingoJS v0.7.0-
  3532. else {
  3533. freeExports.Benchmark = Benchmark;
  3534. }
  3535. }
  3536. // in a browser or Rhino
  3537. else {
  3538. // use square bracket notation so Closure Compiler won't munge `Benchmark`
  3539. // http://code.google.com/closure/compiler/docs/api-tutorial3.html#export
  3540. window['Benchmark'] = Benchmark;
  3541. }
  3542. // trigger clock's lazy define early to avoid a security error
  3543. if (support.air) {
  3544. clock({ '_original': { 'fn': noop, 'count': 1, 'options': {} } });
  3545. }
  3546. }(this));