GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — fext/index.html at master · glathoud/fext Expand file tree/ Copy pathindex.htmlMore file actions executable file ·752 lines (611 loc) · 22.5 KB / Copy pathindex.htmlFile metadata and controlsexecutable file ·752 lines (611 loc) · 22.5 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 <!doctype html> <html> <head> <meta charset="utf-8"> <title>Fast explicit tail calls in JavaScript</title> <link rel="stylesheet" type="text/css" href="web/prettify.css"> <style type="text/css"> body { padding: 0 1em 0 1em; font-family: helvetica; font-family: Verdana,Arial,'Lucida Grande',Sans-Serif; } .title { margin-bottom: 1em; } .right { float: right; } .clear { clear: both; } .text-center { text-align: center; } .intro { margin: auto; text-align: justify; margin-top: 1.5em; } .intro code { line-height: normal; } .top-img { text-align: center; } .section_anchor { display: none; margin-left: 0.5em; } h3:hover .section_anchor { display: initial; } .hidden { display: none; } .small_img { max-width: 6em; margin: 0.5em; } .code_cont { float: left; position: relative; width: calc( 100% - 2em ); padding: 1em; } @media screen and (max-width: 999px) { .right, pre, button, .code_cont_header { font-size: 1.8em; } pre button { font-size: 1.2em; } #speedtest_output { font-size: 0.85em; } h3 { margin-top: 3em; } } @media screen and (min-width: 1200px) { .intro { max-width: 600px; line-height: 1.5em; } .code_cont { width: calc( 50% - 2em ); } } .code_cont_header { margin-top: 2em; background-color: lightgrey; border: solid 1px black; padding: 1em; } .code_o { width: 100%; margin: 0; max-height: 100%; } .code_o.fext_unittest_js { height: 65em; } .code_o.fext_js { height: 435em; } .success { color: darkgreen; } .failure { color: darkred; font-weight: bold;} .speedtest_patience { display: none; } .speedtest_running .speedtest_patience { display: inherit; } .speedtest_running button { display: none; } </style> </head> <body> <a href="https://github.com/glathoud/fext"> <img style="position: fixed; top: 0; right: 0; border: 0; margin: 0; padding: 0;" src="web/forkme_right_green_007200.png" alt="Fork me on GitHub"> </a> <div class="intro"> <div class="top-img"><img class="small_img" src="web/serpent-mord-queue-2.jpg"/></div> <h2 class="title">Fast explicit tail calls in JavaScript</h2> <div class="right">by <a href="../">G. Lathoud</a>, June 2018.</div> <div class="clear" style="margin-bottom: 3em"></div> <p>If you don't know what this is about, please have a look at an excellent <a href="http://2ality.com/2015/06/tail-call-optimization.html">background article</a> on tail calls in JavaScript. Also my own <a href="http://glat.info/pub/tailopt-js/">early work</a> on this might be helpful.</p> <p>In LISP and other languages, tail calls are automatically optimized. In Clojure, there is an explicit keyword <code>recur</code>. Generally, programmers may well not know which "return" statements are optimized by the engine, and which not. This would lead to practical issues when debugging and optimizing [<a href="http://neopythonic.blogspot.de/2009/04/final-words-on-tail-calls.html">2009</a>].</p> <p>What about JavaScript?</p> <p>As of 2018, progress is "slow" and the Chrome team has already <em>removed</em> the automatic self-recursion tail call optimization from its JavaScript engine.</p> <p>Another possibility is to <strong>explicitly mark the tail calls that will be optimized</strong>. JavaScript extensions were proposed that add new keywords to the language [<a href="http://glat.info/js.metaret/">2013</a>] [<a href="https://github.com/tc39/proposal-ptc-syntax">2016</a>].</p> <p>It turns out that we can do this explicit approach using today's JavaScript, without extending the language. <code>fext.js</code> demonstrates this.</p> <p>Mutual recursion is supported. API doc and source on <a href="https://github.com/glathoud/fext">GitHub</a>. Node.js <a href="https://www.npmjs.com/package/fext">package</a>.</p> <p><strong>Update 2019-03-12:</strong> fext is now available <a href="https://github.com/glathoud/d_glat/blob/master/core_fext.d">in the D language as well</a>.</p> <section id="section_quick_example"> <h3>Quick example</h3> <pre class="prettyprint lang-js"><code><script type="text/javascript" src="fext.js"></script> <script type="text/javascript"> var gcd = mfun( (a, b) => a > b ? mret( mself, a-b, b ) : a < b ? mret( mself, b-a, a ) : a ); console.log( gcd( 2*3*5*17, 3*5*19 ) ); // 15 (3*5) </script></code></pre> <section id="section_mutual_recursion_example"> <h3>Mutual recursion example</h3> <pre class="prettyprint lang-js"><code><script type="text/javascript" src="fext.js"></script> <script type="text/javascript"> var isOdd = mfun( function isOdd( n ) { return n > 0 ? mret( isEven, n-1 ) : n < 0 ? mret( mself, -n ) : false ; }) , isEven = mfun( isOdd, function isEven( n ) { return n > 0 ? mret( isOdd, n-1 ) : n < 0 ? mret( mself, -n ) : true ; }) console.log( isOdd( 8951531 ) ); // true ; no call stack issue </script> </code></pre> </section> <section id="section_namespace"> <h3>Namespace alternative</h3> <p>In some situations the globals <code>mfun</code>, <code>meth</code>, <code>mfunD</code>, etc. may feel annoying. Solution: use the <code>fext.*</code> namespace. Below, an example in the Node.js context:</p> <pre class="prettyprint lang-js"><code>var fx = require( '../fext' ).fext; var isOdd = fx.mfun( function isOdd( n ) { return n > 0 ? fx.mret( isEven, n-1 ) : n < 0 ? fx.mret( fx.mself, -n ) : false ; }) , isEven = fx.mfun( isOdd, function isEven( n ) { return n > 0 ? fx.mret( isOdd, n-1 ) : n < 0 ? fx.mret( fx.mself, -n ) : true ; }) console.log( isOdd( 8951531 ) ); // true ; no call stack issue </code></pre> </section> <section id="section_api_doc"> <h3>API Documentation and debugging tools</h3> <p>On <a href="https://github.com/glathoud/fext#api">GitHub</a> (formatted), or directly <a href="README.md">here</a> (unformatted).</p> <p>Debugging: instead of <code>mfun</code> & <code>meth</code>, simply use <code>mfunD</code> & <code>methD</code> to deactivate the optimizations. You can then set breakpoints as usual.</p> </section> <section id="section_speedtest"> <h3>Speed test</h3> <p>These results present the average relative speed (higher is better):</p> <ul> <li><code>100.0</code> is the max of each row,</li> <li>standard deviation in brackets e.g. <code>(2.9)</code>,</li> <li>absolute speed in square brackets, e.g. <code>[5.78e+8]</code> (iterations per second).</li> </ul> <p>The <code>isOdd_mfun</code> and <code>isOdd_mret</code> results show that the proposed approach runs:</p> <ul> <li>similar to, or faster than <code>isOdd_metaret</code>, another approach that extends the JavaScript language with new keywords (<a href="http://glat.info/js.metaret/">2013</a>),</li> <li>much faster than <code>tailtramp</code>, the fastest trampoline implementation I could find (feel free to ping me with a faster one).</li> </ul> <p><strong>So the proposed approach (1) runs very fast and (2) <em>does not need to extend JavaScript with new keywords</em>.</strong></p> <pre><code id="speedtest_output">| Browser | isOdd_mfun | isOdd_meth | isOdd_metaret | isOdd_tailtramp | | :--- | ---: | ---: | ---: | ---: | | Firefox 60 | 95.5 (2.6) | 100.0 (1.4) | 81.2 (0.2) | 0.1 (<0.1) | | | [9.34e+8] | [9.78e+8] | [7.93e+8] | [1.25e+6] | | ---- | ---- | ---- | ---- | ---- | | Chromium 66 | 98.5 (0.3) | 100.0 (4.9) | 52.0 (0.1) | 0.7 (<0.1) | | | [8.87e+8] | [9.00e+8] | [4.68e+8] | [6.12e+6] | | ---- | ---- | ---- | ---- | ---- | | Chrome 67 | 99.8 (0.8) | 100.0 (0.3) | 62.2 (0.2) | 0.8 (<0.1) | | | [7.49e+8] | [7.51e+8] | [4.67e+8] | [6.18e+6] |</code></pre> <p> <button onclick="fext_speedtest(section_speedtest,speedtest_output)">Run</button> <span class="speedtest_patience">Running (please be patient...)</span> </p> </section> <section id="section_unit_tests"> <h3>Unit tests</h3> <pre><code id="unittest_output">Running...</code></pre> </section> <section id="section_longer_example"> <h3>Longer example</h3> <p>Search the first & last indices of a given value in a sorted array that has duplicates:</p> <ul> <li>Code: <a href="#lib_sorted_search_js">lib/sorted_search.js</a> <ul><li>Unittest: <a href="#lib_sorted_search_js__unit_tests">lib/sorted_search.js: unit tests</a></li></ul> </li> <li>Code: <a href="#lib_sorted_search_closure_js">lib/sorted_search_closure.js</a> <ul><li>Unittest: <a href="#lib_sorted_search_closure_js__unit_tests">lib/sorted_search_closure.js: unit tests</a></li></ul> </li> </ul> </section> <section id="section_setup_details_speed_test"> <h3>Annex A: Setup details of the speed test</h3> <p>The <code>isOdd/isEven</code> mutual recursion use case measures well the overhead due to each approach, since both <code>isOdd</code> & <code>isEven</code> do little inside their function bodies.</p> <p>We measure 10 times the duration of <code class="prettyprint lang-js">isOdd( niter )</code> where <code class="prettyprint lang-js">niter</code> is adjusted to have a duration > 1.0 second.</p> <p> <code>isOdd_mfun</code> & <code>isOdd_meth</code> are the proposed approach, using only standard JavaScript, e.g.: <pre class="prettyprint lang-js"><code>var isOdd = mfun( function isOdd( n ) { return n > 0 ? mret( isEven, n-1 ) : n < 0 ? mret( mself, -n ) : false ; }) , isEven = mfun( isOdd, function isEven( n ) { return n > 0 ? mret( isOdd, n-1 ) : n < 0 ? mret( mself, -n ) : true ; })</code></pre> <p><code>isOdd_metaret</code> is another approach that extends the JavaScript language with new keywords, including <code>metafun</code> and <code>metaret</code> (<a href="http://glat.info/js.metaret/">2013</a>):</p> <pre class="prettyprint lang-js"><code>metafun isEven( self, n ) { if (n > 0) metaret isOdd, n - 1; // mutual recursion if (n < 0) metaret self, -n; return true; } metafun isOdd( self, n ) { if (n > 0) metaret isEven, n - 1; if (n < 0) metaret self, -n; return false; }</code></pre> <p>and <code>isOdd_tailtramp</code> is the fastest trampoline implementation that I could find:</p> <pre class="prettyprint lang-js"><code>var isOdd = tailtramp( function( n ) { return n > 0 ? isEven( n-1 ) : n < 0 ? isOdd( -n ) : false ; }) , isEven = tailtramp( function( n ) { return n > 0 ? isOdd( n-1 ) : n < 0 ? isEven( -n ) : true ; }) function tailtramp(g) { var tailtramp_n = 0; return tailtramp_impl; function tailtramp_impl() { var arr = [g, this, arguments] , ret; // Jump off a small Empire State Building if (tailtramp_n>5) return new TailCall(arr); while (true) { tailtramp_n++; ret = arr[0].apply(arr[1], arr[2]); tailtramp_n--; if (!(ret instanceof TailCall)) { tailtramp_n = 0; return ret; } // Hit 33rd Street and bounce again arr = ret.arr; } } } function TailCall(arr) { this.arr = arr; }</code></pre> </section> <section id="section_annex_speedup_recursive_expansion"> <h3>Annex B: Speedup through recursive expansion</h3> <p>To reduce the number of CPU jumps, several levels of recursion are automatically expanded and inlined. For an example, have a look at the code generated for <code>gcd</code>: </p> <pre class="prettyprint lang-js"><code>var gcd = mfun( (a, b) => a > b ? mret( mself, a-b, b ) : a < b ? mret( mself, b-a, a ) : a ); console.log(gcd._tf_get_bodycode());</code></pre> <p>Result:</p> <pre class="prettyprint lang-js" style="max-height: 20em; overflow: scroll;"><code>"use strict"; var that = this, __fext_case_i__ = 0, __fext_ret__, __fext_arg_a__, __fext_arg_b__ ; __fext_main_loop__: for (;;) { switch( __fext_case_i__) { case 0: __fext_inline_loop_1__: for(;;) { /*return a > b ? mret( mself, a-b, b ) : a < b ? mret( mself, b-a, a ) : a;*/ {if (a > b) { { (__fext_arg_a__ = a-b, __fext_arg_b__ = b, a = __fext_arg_a__, b = __fext_arg_b__) ; } break __fext_inline_loop_1__; } if (a < b) { { (__fext_arg_a__ = b-a, __fext_arg_b__ = a, a = __fext_arg_a__, b = __fext_arg_b__) ; } break __fext_inline_loop_1__; } { { return a ; } break __fext_inline_loop_1__; } } } if (__fext_case_i__ === -1) return __fext_ret__; __fext_inline_loop_2__: for(;;) { /*return a > b ? mret( mself, a-b, b ) : a < b ? mret( mself, b-a, a ) : a;*/ {if (a > b) { { (__fext_arg_a__ = a-b, __fext_arg_b__ = b, a = __fext_arg_a__, b = __fext_arg_b__) ; } break __fext_inline_loop_2__; } if (a < b) { { (__fext_arg_a__ = b-a, __fext_arg_b__ = a, a = __fext_arg_a__, b = __fext_arg_b__) ; } break __fext_inline_loop_2__; } { { return a ; } break __fext_inline_loop_2__; } } } if (__fext_case_i__ === -1) return __fext_ret__; __fext_inline_loop_3__: for(;;) { /*return a > b ? mret( mself, a-b, b ) : a < b ? mret( mself, b-a, a ) : a;*/ {if (a > b) { { (__fext_arg_a__ = a-b, __fext_arg_b__ = b, a = __fext_arg_a__, b = __fext_arg_b__) ; } break __fext_inline_loop_3__; } if (a < b) { { (__fext_arg_a__ = b-a, __fext_arg_b__ = a, a = __fext_arg_a__, b = __fext_arg_b__) ; } break __fext_inline_loop_3__; } { { return a ; } break __fext_inline_loop_3__; } } } if (__fext_case_i__ === -1) return __fext_ret__; __fext_inline_loop_4__: for(;;) { /*return a > b ? mret( mself, a-b, b ) : a < b ? mret( mself, b-a, a ) : a;*/ {if (a > b) { { (__fext_arg_a__ = a-b, __fext_arg_b__ = b, a = __fext_arg_a__, b = __fext_arg_b__) ; } break __fext_inline_loop_4__; } if (a < b) { { (__fext_arg_a__ = b-a, __fext_arg_b__ = a, a = __fext_arg_a__, b = __fext_arg_b__) ; } break __fext_inline_loop_4__; } { { return a ; } break __fext_inline_loop_4__; } } } if (__fext_case_i__ === -1) return __fext_ret__; /*return a > b ? mret( mself, a-b, b ) : a < b ? mret( mself, b-a, a ) : a;*/ {if (a > b) { { (__fext_arg_a__ = a-b, __fext_arg_b__ = b, a = __fext_arg_a__, b = __fext_arg_b__) ; } continue __fext_main_loop__; } if (a < b) { { (__fext_arg_a__ = b-a, __fext_arg_b__ = a, a = __fext_arg_a__, b = __fext_arg_b__) ; } continue __fext_main_loop__; } { { return a ; } continue __fext_main_loop__; } } continue __fext_main_loop__; default: return __fext_ret__; } }</code></pre> <p>Looks overcomplicated? In practice, debugging is not a problem since one can anytime reverse to the non-optimized implementation using <code>mfunD</code> and <code>methD</code>: </p> <pre class="prettyprint lang-js"><code>var gcd = mfunD( (a, b) => a > b ? mret( mself, a-b, b ) : a < b ? mret( mself, b-a, a ) : a ); console.log(gcd._tf_get_dbg_f_code());</code></pre> <p>Result:</p> <pre class="prettyprint lang-js"><code>(a, b) => a > b ? mret( mself, a-b, b ) : a < b ? mret( mself, b-a, a ) : a</code></pre> <p>...indeed, the unmodified source code, which will run as it is.</p> </section> <section id="section_annex_more_code"> <h3>Annex C: More code</h3> <p>On <a href="https://github.com/glathoud/fext/">GitHub</a> and here below.</p> <p id="toccont"> <ul id="toc"></ul> </p> </section> </div> <div id="source_code_0" class="code_cont"></div> <div id="source_code_1" class="code_cont"></div> <script type="text/html" id="source_code_tmpl"> <p class="code_cont_header" id="$domid">$filename:</p> <pre><code class="prettyprint lang-js">$sourcecode</code></pre> </script> <script type="text/html" id="toctmpl"> <li><a href="#$domid">$filename</a></li> </script> <script type="text/javascript" src="fext.js"></script> <script type="text/javascript" src="lib/sorted_search.js"></script> <script type="text/javascript" src="lib/sorted_search_closure.js"></script> <script type="text/javascript" src="lib/sorted_search_unittest.js"></script> <script type="text/javascript" src="lib/sorted_search_closure_unittest.js"></script> <script type="text/javascript" src="test/fext_unittest.js"></script> <script type="text/javascript" src="test/fext_unittest_es6.js"></script> <script type="text/javascript" src="web/prettify.js"></script> <script type="text/javascript"> //' (function () { var cstmpl = window.source_code_tmpl; if (cstmpl) { cstmpl.parentNode.removeChild( cstmpl ); window.toccont && (toccont.style.display = 'none'); } var to_write = []; setup_section_anchors(); if (cstmpl && window.source_code_0 && window.source_code_1) { write_source_code( source_code_0, "lib/sorted_search.js" ) write_source_code( source_code_0, "lib/sorted_search_closure.js" ) write_source_code( source_code_1, get_test_arr_sorted_search, "lib/sorted_search.js: unit tests" ); write_source_code( source_code_1, get_test_arr_sorted_search_closure, "lib/sorted_search_closure.js: unit tests" ); } else { do_the_unittests(); } function write_source_code( contnode, x, opt ) { var i_write = write_source_code.n | 0; write_source_code.n = 1 + i_write; if ('function' === typeof x) { var filename = opt || x.name , c_arr = x().map( unindent ) ; setTimeout( function () { receive_source_code( { target : { responseText : c_arr.join( '\n\n\n' ) } } ); }, 100 ); } else { var filename = x , xhr = new XMLHttpRequest() ; try { xhr.addEventListener( "load", receive_source_code ); xhr.open( "GET", filename, /*async:*/true ); xhr.send(); } catch( e ) { write_source_code.n--; return; } } if (window.toc && window.toctmpl) { toc.innerHTML += format( toctmpl.innerHTML, filename ); } function unindent( f ) { var s = '' + f , first = /\n\s+/.exec( s ) ; return first ? s.replace( new RegExp( first[ 0 ], 'g' ) , '\n' ) : s; } function receive_source_code( a ) { var et = a && a.target , etr = et && (et.response || et.responseText) , domid = filename.replace(/\W/g,'_') ; to_write[ i_write ] = function () { contnode.innerHTML += format( cstmpl.innerHTML, filename, etr ); }; if (--write_source_code.n < 1) { to_write.forEach( function( f ) { f(); } ); prettyPrint(); window.toccont && (toccont.style.display = ''); setTimeout( do_the_unittests, 2000 ); } } } function format( tmpl, filename, sourcecode ) { var domid = filename.replace(/\W/g,'_') , ret = tmpl .replace( /\$filename\b/g, filename) .replace( /\$domid\b/g, domid ) ; if (sourcecode) { ret = ret.replace( /\$sourcecode\b/g , sourcecode .replace( /</g, '<' ) .replace( />/g, '>' ) ); } return ret; } function do_the_unittests() { fext_unittest( function ( result ) { unittest_output.innerHTML = result.text.replace( /^\s+/, '' ); } ); } function setup_section_anchors() { document.querySelectorAll('[id^="section_"]') .forEach( setup_one_section_anchor ) ; } function setup_one_section_anchor( cont ) { var h3 = cont.querySelector('h3') , a = document.createElement('a') ; a.setAttribute( 'href','#' + cont.id ); a.textContent='#'; a.setAttribute( 'class','section_anchor' ); h3.append( a ); } })(); </script> <script type="text/javascript" src="test/fext_speedtest.js"></script> </body> </html> |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |