splay.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  1. // Copyright 2013 the V8 project authors. All rights reserved.
  2. // Redistribution and use in source and binary forms, with or without
  3. // modification, are permitted provided that the following conditions are
  4. // met:
  5. //
  6. // * Redistributions of source code must retain the above copyright
  7. // notice, this list of conditions and the following disclaimer.
  8. // * Redistributions in binary form must reproduce the above
  9. // copyright notice, this list of conditions and the following
  10. // disclaimer in the documentation and/or other materials provided
  11. // with the distribution.
  12. // * Neither the name of Google Inc. nor the names of its
  13. // contributors may be used to endorse or promote products derived
  14. // from this software without specific prior written permission.
  15. //
  16. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  17. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  18. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  19. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  20. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  21. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  22. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  23. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  24. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  25. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  26. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  27. // Performance.now is used in latency benchmarks, the fallback is Date.now.
  28. var performance = performance || {};
  29. performance.now = (function() {
  30. return performance.now ||
  31. performance.mozNow ||
  32. performance.msNow ||
  33. performance.oNow ||
  34. performance.webkitNow ||
  35. Date.now;
  36. })();
  37. // Simple framework for running the benchmark suites and
  38. // computing a score based on the timing measurements.
  39. // A benchmark has a name (string) and a function that will be run to
  40. // do the performance measurement. The optional setup and tearDown
  41. // arguments are functions that will be invoked before and after
  42. // running the benchmark, but the running time of these functions will
  43. // not be accounted for in the benchmark score.
  44. function Benchmark(name, doWarmup, doDeterministic, deterministicIterations,
  45. run, setup, tearDown, rmsResult, minIterations) {
  46. this.name = name;
  47. this.doWarmup = doWarmup;
  48. this.doDeterministic = doDeterministic;
  49. this.deterministicIterations = deterministicIterations;
  50. this.run = run;
  51. this.Setup = setup ? setup : function() { };
  52. this.TearDown = tearDown ? tearDown : function() { };
  53. this.rmsResult = rmsResult ? rmsResult : null;
  54. this.minIterations = minIterations ? minIterations : 32;
  55. }
  56. // Benchmark results hold the benchmark and the measured time used to
  57. // run the benchmark. The benchmark score is computed later once a
  58. // full benchmark suite has run to completion. If latency is set to 0
  59. // then there is no latency score for this benchmark.
  60. function BenchmarkResult(benchmark, time, latency) {
  61. this.benchmark = benchmark;
  62. this.time = time;
  63. this.latency = latency;
  64. }
  65. // Automatically convert results to numbers. Used by the geometric
  66. // mean computation.
  67. BenchmarkResult.prototype.valueOf = function() {
  68. return this.time;
  69. }
  70. // Suites of benchmarks consist of a name and the set of benchmarks in
  71. // addition to the reference timing that the final score will be based
  72. // on. This way, all scores are relative to a reference run and higher
  73. // scores implies better performance.
  74. function BenchmarkSuite(name, reference, benchmarks) {
  75. this.name = name;
  76. this.reference = reference;
  77. this.benchmarks = benchmarks;
  78. BenchmarkSuite.suites.push(this);
  79. }
  80. // Keep track of all declared benchmark suites.
  81. BenchmarkSuite.suites = [];
  82. // Scores are not comparable across versions. Bump the version if
  83. // you're making changes that will affect that scores, e.g. if you add
  84. // a new benchmark or change an existing one.
  85. BenchmarkSuite.version = '9';
  86. // Defines global benchsuite running mode that overrides benchmark suite
  87. // behavior. Intended to be set by the benchmark driver. Undefined
  88. // values here allow a benchmark to define behaviour itself.
  89. BenchmarkSuite.config = {
  90. doWarmup: undefined,
  91. doDeterministic: undefined
  92. };
  93. // Override the alert function to throw an exception instead.
  94. alert = function(s) {
  95. throw "Alert called with argument: " + s;
  96. };
  97. // To make the benchmark results predictable, we replace Math.random
  98. // with a 100% deterministic alternative.
  99. BenchmarkSuite.ResetRNG = function() {
  100. Math.random = (function() {
  101. var seed = 49734321;
  102. return function() {
  103. // Robert Jenkins' 32 bit integer hash function.
  104. seed = ((seed + 0x7ed55d16) + (seed << 12)) & 0xffffffff;
  105. seed = ((seed ^ 0xc761c23c) ^ (seed >>> 19)) & 0xffffffff;
  106. seed = ((seed + 0x165667b1) + (seed << 5)) & 0xffffffff;
  107. seed = ((seed + 0xd3a2646c) ^ (seed << 9)) & 0xffffffff;
  108. seed = ((seed + 0xfd7046c5) + (seed << 3)) & 0xffffffff;
  109. seed = ((seed ^ 0xb55a4f09) ^ (seed >>> 16)) & 0xffffffff;
  110. return (seed & 0xfffffff) / 0x10000000;
  111. };
  112. })();
  113. }
  114. // Runs all registered benchmark suites and optionally yields between
  115. // each individual benchmark to avoid running for too long in the
  116. // context of browsers. Once done, the final score is reported to the
  117. // runner.
  118. BenchmarkSuite.RunSuites = function(runner, skipBenchmarks) {
  119. skipBenchmarks = typeof skipBenchmarks === 'undefined' ? [] : skipBenchmarks;
  120. var continuation = null;
  121. var suites = BenchmarkSuite.suites;
  122. var length = suites.length;
  123. BenchmarkSuite.scores = [];
  124. var index = 0;
  125. function RunStep() {
  126. while (continuation || index < length) {
  127. if (continuation) {
  128. continuation = continuation();
  129. } else {
  130. var suite = suites[index++];
  131. if (runner.NotifyStart) runner.NotifyStart(suite.name);
  132. if (skipBenchmarks.indexOf(suite.name) > -1) {
  133. suite.NotifySkipped(runner);
  134. } else {
  135. continuation = suite.RunStep(runner);
  136. }
  137. }
  138. if (continuation && typeof window != 'undefined' && window.setTimeout) {
  139. window.setTimeout(RunStep, 25);
  140. return;
  141. }
  142. }
  143. // show final result
  144. if (runner.NotifyScore) {
  145. var score = BenchmarkSuite.GeometricMean(BenchmarkSuite.scores);
  146. var formatted = BenchmarkSuite.FormatScore(100 * score);
  147. runner.NotifyScore(formatted);
  148. }
  149. }
  150. RunStep();
  151. }
  152. // Counts the total number of registered benchmarks. Useful for
  153. // showing progress as a percentage.
  154. BenchmarkSuite.CountBenchmarks = function() {
  155. var result = 0;
  156. var suites = BenchmarkSuite.suites;
  157. for (var i = 0; i < suites.length; i++) {
  158. result += suites[i].benchmarks.length;
  159. }
  160. return result;
  161. }
  162. // Computes the geometric mean of a set of numbers.
  163. BenchmarkSuite.GeometricMean = function(numbers) {
  164. var log = 0;
  165. for (var i = 0; i < numbers.length; i++) {
  166. log += Math.log(numbers[i]);
  167. }
  168. return Math.pow(Math.E, log / numbers.length);
  169. }
  170. // Computes the geometric mean of a set of throughput time measurements.
  171. BenchmarkSuite.GeometricMeanTime = function(measurements) {
  172. var log = 0;
  173. for (var i = 0; i < measurements.length; i++) {
  174. log += Math.log(measurements[i].time);
  175. }
  176. return Math.pow(Math.E, log / measurements.length);
  177. }
  178. // Computes the geometric mean of a set of rms measurements.
  179. BenchmarkSuite.GeometricMeanLatency = function(measurements) {
  180. var log = 0;
  181. var hasLatencyResult = false;
  182. for (var i = 0; i < measurements.length; i++) {
  183. if (measurements[i].latency != 0) {
  184. log += Math.log(measurements[i].latency);
  185. hasLatencyResult = true;
  186. }
  187. }
  188. if (hasLatencyResult) {
  189. return Math.pow(Math.E, log / measurements.length);
  190. } else {
  191. return 0;
  192. }
  193. }
  194. // Converts a score value to a string with at least three significant
  195. // digits.
  196. BenchmarkSuite.FormatScore = function(value) {
  197. if (value > 100) {
  198. return value.toFixed(0);
  199. } else {
  200. return value.toPrecision(3);
  201. }
  202. }
  203. // Notifies the runner that we're done running a single benchmark in
  204. // the benchmark suite. This can be useful to report progress.
  205. BenchmarkSuite.prototype.NotifyStep = function(result) {
  206. this.results.push(result);
  207. if (this.runner.NotifyStep) this.runner.NotifyStep(result.benchmark.name);
  208. }
  209. // Notifies the runner that we're done with running a suite and that
  210. // we have a result which can be reported to the user if needed.
  211. BenchmarkSuite.prototype.NotifyResult = function() {
  212. var mean = BenchmarkSuite.GeometricMeanTime(this.results);
  213. var score = this.reference[0] / mean;
  214. BenchmarkSuite.scores.push(score);
  215. if (this.runner.NotifyResult) {
  216. var formatted = BenchmarkSuite.FormatScore(100 * score);
  217. this.runner.NotifyResult("SCORE", formatted);
  218. }
  219. if (this.reference.length == 2) {
  220. var meanLatency = BenchmarkSuite.GeometricMeanLatency(this.results);
  221. if (meanLatency != 0) {
  222. var scoreLatency = this.reference[1] / meanLatency;
  223. BenchmarkSuite.scores.push(scoreLatency);
  224. if (this.runner.NotifyResult) {
  225. var formattedLatency = BenchmarkSuite.FormatScore(100 * scoreLatency)
  226. this.runner.NotifyResult("LATENCY", formattedLatency);
  227. }
  228. }
  229. }
  230. }
  231. BenchmarkSuite.prototype.NotifySkipped = function(runner) {
  232. BenchmarkSuite.scores.push(1); // push default reference score.
  233. if (runner.NotifyResult) {
  234. runner.NotifyResult(this.name, "Skipped");
  235. }
  236. }
  237. // Notifies the runner that running a benchmark resulted in an error.
  238. BenchmarkSuite.prototype.NotifyError = function(error) {
  239. if (this.runner.NotifyError) {
  240. this.runner.NotifyError(this.name, error);
  241. }
  242. if (this.runner.NotifyStep) {
  243. this.runner.NotifyStep(this.name);
  244. }
  245. }
  246. // Runs a single benchmark for at least a second and computes the
  247. // average time it takes to run a single iteration.
  248. BenchmarkSuite.prototype.RunSingleBenchmark = function(benchmark, data) {
  249. var config = BenchmarkSuite.config;
  250. var doWarmup = config.doWarmup !== undefined
  251. ? config.doWarmup
  252. : benchmark.doWarmup;
  253. var doDeterministic = config.doDeterministic !== undefined
  254. ? config.doDeterministic
  255. : benchmark.doDeterministic;
  256. function Measure(data) {
  257. var elapsed = 0;
  258. var start = new Date();
  259. // Run either for 1 second or for the number of iterations specified
  260. // by minIterations, depending on the config flag doDeterministic.
  261. for (var i = 0; (doDeterministic ?
  262. i<benchmark.deterministicIterations : elapsed < 1000); i++) {
  263. benchmark.run();
  264. elapsed = new Date() - start;
  265. }
  266. if (data != null) {
  267. data.runs += i;
  268. data.elapsed += elapsed;
  269. }
  270. }
  271. // Sets up data in order to skip or not the warmup phase.
  272. if (!doWarmup && data == null) {
  273. data = { runs: 0, elapsed: 0 };
  274. }
  275. if (data == null) {
  276. Measure(null);
  277. return { runs: 0, elapsed: 0 };
  278. } else {
  279. Measure(data);
  280. // If we've run too few iterations, we continue for another second.
  281. if (data.runs < benchmark.minIterations) return data;
  282. var usec = (data.elapsed * 1000) / data.runs;
  283. var rms = (benchmark.rmsResult != null) ? benchmark.rmsResult() : 0;
  284. this.NotifyStep(new BenchmarkResult(benchmark, usec, rms));
  285. return null;
  286. }
  287. }
  288. // This function starts running a suite, but stops between each
  289. // individual benchmark in the suite and returns a continuation
  290. // function which can be invoked to run the next benchmark. Once the
  291. // last benchmark has been executed, null is returned.
  292. BenchmarkSuite.prototype.RunStep = function(runner) {
  293. BenchmarkSuite.ResetRNG();
  294. this.results = [];
  295. this.runner = runner;
  296. var length = this.benchmarks.length;
  297. var index = 0;
  298. var suite = this;
  299. var data;
  300. // Run the setup, the actual benchmark, and the tear down in three
  301. // separate steps to allow the framework to yield between any of the
  302. // steps.
  303. function RunNextSetup() {
  304. if (index < length) {
  305. try {
  306. suite.benchmarks[index].Setup();
  307. } catch (e) {
  308. suite.NotifyError(e);
  309. return null;
  310. }
  311. return RunNextBenchmark;
  312. }
  313. suite.NotifyResult();
  314. return null;
  315. }
  316. function RunNextBenchmark() {
  317. try {
  318. data = suite.RunSingleBenchmark(suite.benchmarks[index], data);
  319. } catch (e) {
  320. suite.NotifyError(e);
  321. return null;
  322. }
  323. // If data is null, we're done with this benchmark.
  324. return (data == null) ? RunNextTearDown : RunNextBenchmark();
  325. }
  326. function RunNextTearDown() {
  327. try {
  328. suite.benchmarks[index++].TearDown();
  329. } catch (e) {
  330. suite.NotifyError(e);
  331. return null;
  332. }
  333. return RunNextSetup;
  334. }
  335. // Start out running the setup.
  336. return RunNextSetup();
  337. }
  338. // Copyright 2009 the V8 project authors. All rights reserved.
  339. // Redistribution and use in source and binary forms, with or without
  340. // modification, are permitted provided that the following conditions are
  341. // met:
  342. //
  343. // * Redistributions of source code must retain the above copyright
  344. // notice, this list of conditions and the following disclaimer.
  345. // * Redistributions in binary form must reproduce the above
  346. // copyright notice, this list of conditions and the following
  347. // disclaimer in the documentation and/or other materials provided
  348. // with the distribution.
  349. // * Neither the name of Google Inc. nor the names of its
  350. // contributors may be used to endorse or promote products derived
  351. // from this software without specific prior written permission.
  352. //
  353. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  354. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  355. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  356. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  357. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  358. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  359. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  360. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  361. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  362. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  363. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  364. // This benchmark is based on a JavaScript log processing module used
  365. // by the V8 profiler to generate execution time profiles for runs of
  366. // JavaScript applications, and it effectively measures how fast the
  367. // JavaScript engine is at allocating nodes and reclaiming the memory
  368. // used for old nodes. Because of the way splay trees work, the engine
  369. // also has to deal with a lot of changes to the large tree object
  370. // graph.
  371. var Splay = new BenchmarkSuite('Splay', [81491, 2739514], [
  372. new Benchmark("Splay", true, false, 1400,
  373. SplayRun, SplaySetup, SplayTearDown, SplayRMS)
  374. ]);
  375. // Configuration.
  376. var kSplayTreeSize = 8000;
  377. var kSplayTreeModifications = 80;
  378. var kSplayTreePayloadDepth = 5;
  379. var splayTree = null;
  380. var splaySampleTimeStart = 0.0;
  381. function GeneratePayloadTree(depth, tag) {
  382. if (depth == 0) {
  383. return {
  384. array : [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ],
  385. string : 'String for key ' + tag + ' in leaf node'
  386. };
  387. } else {
  388. return {
  389. left: GeneratePayloadTree(depth - 1, tag),
  390. right: GeneratePayloadTree(depth - 1, tag)
  391. };
  392. }
  393. }
  394. function GenerateKey() {
  395. // The benchmark framework guarantees that Math.random is
  396. // deterministic; see base.js.
  397. return Math.random();
  398. }
  399. var splaySamples = 0;
  400. var splaySumOfSquaredPauses = 0;
  401. function SplayRMS() {
  402. return Math.round(Math.sqrt(splaySumOfSquaredPauses / splaySamples) * 10000);
  403. }
  404. function SplayUpdateStats(time) {
  405. var pause = time - splaySampleTimeStart;
  406. splaySampleTimeStart = time;
  407. splaySamples++;
  408. splaySumOfSquaredPauses += pause * pause;
  409. }
  410. function InsertNewNode() {
  411. // Insert new node with a unique key.
  412. var key;
  413. do {
  414. key = GenerateKey();
  415. } while (splayTree.find(key) != null);
  416. var payload = GeneratePayloadTree(kSplayTreePayloadDepth, String(key));
  417. splayTree.insert(key, payload);
  418. return key;
  419. }
  420. function SplaySetup() {
  421. // Check if the platform has the performance.now high resolution timer.
  422. // If not, throw exception and quit.
  423. if (!performance.now) {
  424. throw "PerformanceNowUnsupported";
  425. }
  426. splayTree = new SplayTree();
  427. splaySampleTimeStart = performance.now()
  428. for (var i = 0; i < kSplayTreeSize; i++) {
  429. InsertNewNode();
  430. if ((i+1) % 20 == 19) {
  431. SplayUpdateStats(performance.now());
  432. }
  433. }
  434. }
  435. function SplayTearDown() {
  436. // Allow the garbage collector to reclaim the memory
  437. // used by the splay tree no matter how we exit the
  438. // tear down function.
  439. var keys = splayTree.exportKeys();
  440. splayTree = null;
  441. splaySamples = 0;
  442. splaySumOfSquaredPauses = 0;
  443. // Verify that the splay tree has the right size.
  444. var length = keys.length;
  445. if (length != kSplayTreeSize) {
  446. throw new Error("Splay tree has wrong size");
  447. }
  448. // Verify that the splay tree has sorted, unique keys.
  449. for (var i = 0; i < length - 1; i++) {
  450. if (keys[i] >= keys[i + 1]) {
  451. throw new Error("Splay tree not sorted");
  452. }
  453. }
  454. }
  455. function SplayRun() {
  456. // Replace a few nodes in the splay tree.
  457. for (var i = 0; i < kSplayTreeModifications; i++) {
  458. var key = InsertNewNode();
  459. var greatest = splayTree.findGreatestLessThan(key);
  460. if (greatest == null) splayTree.remove(key);
  461. else splayTree.remove(greatest.key);
  462. }
  463. SplayUpdateStats(performance.now());
  464. }
  465. /**
  466. * Constructs a Splay tree. A splay tree is a self-balancing binary
  467. * search tree with the additional property that recently accessed
  468. * elements are quick to access again. It performs basic operations
  469. * such as insertion, look-up and removal in O(log(n)) amortized time.
  470. *
  471. * @constructor
  472. */
  473. function SplayTree() {
  474. };
  475. /**
  476. * Pointer to the root node of the tree.
  477. *
  478. * @type {SplayTree.Node}
  479. * @private
  480. */
  481. SplayTree.prototype.root_ = null;
  482. /**
  483. * @return {boolean} Whether the tree is empty.
  484. */
  485. SplayTree.prototype.isEmpty = function() {
  486. return !this.root_;
  487. };
  488. /**
  489. * Inserts a node into the tree with the specified key and value if
  490. * the tree does not already contain a node with the specified key. If
  491. * the value is inserted, it becomes the root of the tree.
  492. *
  493. * @param {number} key Key to insert into the tree.
  494. * @param {*} value Value to insert into the tree.
  495. */
  496. SplayTree.prototype.insert = function(key, value) {
  497. if (this.isEmpty()) {
  498. this.root_ = new SplayTree.Node(key, value);
  499. return;
  500. }
  501. // Splay on the key to move the last node on the search path for
  502. // the key to the root of the tree.
  503. this.splay_(key);
  504. if (this.root_.key == key) {
  505. return;
  506. }
  507. var node = new SplayTree.Node(key, value);
  508. if (key > this.root_.key) {
  509. node.left = this.root_;
  510. node.right = this.root_.right;
  511. this.root_.right = null;
  512. } else {
  513. node.right = this.root_;
  514. node.left = this.root_.left;
  515. this.root_.left = null;
  516. }
  517. this.root_ = node;
  518. };
  519. /**
  520. * Removes a node with the specified key from the tree if the tree
  521. * contains a node with this key. The removed node is returned. If the
  522. * key is not found, an exception is thrown.
  523. *
  524. * @param {number} key Key to find and remove from the tree.
  525. * @return {SplayTree.Node} The removed node.
  526. */
  527. SplayTree.prototype.remove = function(key) {
  528. if (this.isEmpty()) {
  529. throw Error('Key not found: ' + key);
  530. }
  531. this.splay_(key);
  532. if (this.root_.key != key) {
  533. throw Error('Key not found: ' + key);
  534. }
  535. var removed = this.root_;
  536. if (!this.root_.left) {
  537. this.root_ = this.root_.right;
  538. } else {
  539. var right = this.root_.right;
  540. this.root_ = this.root_.left;
  541. // Splay to make sure that the new root has an empty right child.
  542. this.splay_(key);
  543. // Insert the original right child as the right child of the new
  544. // root.
  545. this.root_.right = right;
  546. }
  547. return removed;
  548. };
  549. /**
  550. * Returns the node having the specified key or null if the tree doesn't contain
  551. * a node with the specified key.
  552. *
  553. * @param {number} key Key to find in the tree.
  554. * @return {SplayTree.Node} Node having the specified key.
  555. */
  556. SplayTree.prototype.find = function(key) {
  557. if (this.isEmpty()) {
  558. return null;
  559. }
  560. this.splay_(key);
  561. return this.root_.key == key ? this.root_ : null;
  562. };
  563. /**
  564. * @return {SplayTree.Node} Node having the maximum key value.
  565. */
  566. SplayTree.prototype.findMax = function(opt_startNode) {
  567. if (this.isEmpty()) {
  568. return null;
  569. }
  570. var current = opt_startNode || this.root_;
  571. while (current.right) {
  572. current = current.right;
  573. }
  574. return current;
  575. };
  576. /**
  577. * @return {SplayTree.Node} Node having the maximum key value that
  578. * is less than the specified key value.
  579. */
  580. SplayTree.prototype.findGreatestLessThan = function(key) {
  581. if (this.isEmpty()) {
  582. return null;
  583. }
  584. // Splay on the key to move the node with the given key or the last
  585. // node on the search path to the top of the tree.
  586. this.splay_(key);
  587. // Now the result is either the root node or the greatest node in
  588. // the left subtree.
  589. if (this.root_.key < key) {
  590. return this.root_;
  591. } else if (this.root_.left) {
  592. return this.findMax(this.root_.left);
  593. } else {
  594. return null;
  595. }
  596. };
  597. /**
  598. * @return {Array<*>} An array containing all the keys of tree's nodes.
  599. */
  600. SplayTree.prototype.exportKeys = function() {
  601. var result = [];
  602. if (!this.isEmpty()) {
  603. this.root_.traverse_(function(node) { result.push(node.key); });
  604. }
  605. return result;
  606. };
  607. /**
  608. * Perform the splay operation for the given key. Moves the node with
  609. * the given key to the top of the tree. If no node has the given
  610. * key, the last node on the search path is moved to the top of the
  611. * tree. This is the simplified top-down splaying algorithm from:
  612. * "Self-adjusting Binary Search Trees" by Sleator and Tarjan
  613. *
  614. * @param {number} key Key to splay the tree on.
  615. * @private
  616. */
  617. SplayTree.prototype.splay_ = function(key) {
  618. if (this.isEmpty()) {
  619. return;
  620. }
  621. // Create a dummy node. The use of the dummy node is a bit
  622. // counter-intuitive: The right child of the dummy node will hold
  623. // the L tree of the algorithm. The left child of the dummy node
  624. // will hold the R tree of the algorithm. Using a dummy node, left
  625. // and right will always be nodes and we avoid special cases.
  626. var dummy, left, right;
  627. dummy = left = right = new SplayTree.Node(null, null);
  628. var current = this.root_;
  629. while (true) {
  630. if (key < current.key) {
  631. if (!current.left) {
  632. break;
  633. }
  634. if (key < current.left.key) {
  635. // Rotate right.
  636. var tmp = current.left;
  637. current.left = tmp.right;
  638. tmp.right = current;
  639. current = tmp;
  640. if (!current.left) {
  641. break;
  642. }
  643. }
  644. // Link right.
  645. right.left = current;
  646. right = current;
  647. current = current.left;
  648. } else if (key > current.key) {
  649. if (!current.right) {
  650. break;
  651. }
  652. if (key > current.right.key) {
  653. // Rotate left.
  654. var tmp = current.right;
  655. current.right = tmp.left;
  656. tmp.left = current;
  657. current = tmp;
  658. if (!current.right) {
  659. break;
  660. }
  661. }
  662. // Link left.
  663. left.right = current;
  664. left = current;
  665. current = current.right;
  666. } else {
  667. break;
  668. }
  669. }
  670. // Assemble.
  671. left.right = current.left;
  672. right.left = current.right;
  673. current.left = dummy.right;
  674. current.right = dummy.left;
  675. this.root_ = current;
  676. };
  677. /**
  678. * Constructs a Splay tree node.
  679. *
  680. * @param {number} key Key.
  681. * @param {*} value Value.
  682. */
  683. SplayTree.Node = function(key, value) {
  684. this.key = key;
  685. this.value = value;
  686. };
  687. /**
  688. * @type {SplayTree.Node}
  689. */
  690. SplayTree.Node.prototype.left = null;
  691. /**
  692. * @type {SplayTree.Node}
  693. */
  694. SplayTree.Node.prototype.right = null;
  695. /**
  696. * Performs an ordered traversal of the subtree starting at
  697. * this SplayTree.Node.
  698. *
  699. * @param {function(SplayTree.Node)} f Visitor function.
  700. * @private
  701. */
  702. SplayTree.Node.prototype.traverse_ = function(f) {
  703. var current = this;
  704. while (current) {
  705. var left = current.left;
  706. if (left) left.traverse_(f);
  707. f(current);
  708. current = current.right;
  709. }
  710. };
  711. ////////////////////////////////////////////////////////////////////////////////
  712. // Runner
  713. ////////////////////////////////////////////////////////////////////////////////
  714. var success = true;
  715. function NotifyStart(name) {
  716. }
  717. function NotifyError(name, error) {
  718. WScript.Echo(name + " : ERROR : " + error.stack);
  719. success = false;
  720. }
  721. function NotifyResult(name, score) {
  722. if (success) {
  723. WScript.Echo("### " + name + ":", score);
  724. }
  725. }
  726. function NotifyScore(score) {
  727. }
  728. BenchmarkSuite.RunSuites({
  729. NotifyStart: NotifyStart,
  730. NotifyError: NotifyError,
  731. NotifyResult: NotifyResult,
  732. NotifyScore: NotifyScore
  733. });