Of course a loop is even faster...

#!perl use strict; use Benchmark qw(cmpthese); my %counter; sub normal { return 0 unless $_[0]; @_ = ($_[0] - 1); $counter{(caller(0))[3]}++; return normal(@_); } sub tail { return 0 unless $_[0]; @_ = ($_[0] - 1); $counter{(caller(0))[3]}++; goto &tail; } sub faster { return 0 unless $_[0]; @_ = ($_[0] - 1); $counter{(caller(0))[3]}++; &faster; } sub loop { for (0..$_[0]) { $counter{(caller(0))[3]}++; } return 0; } cmpthese( -3, { "normal" => sub { normal(50000) }, "tail" => sub { tail(50000) }, "faster" => sub { faster(50000) }, "loop" => sub { loop(50000) }, } ); __END__ Rate normal tail faster loop normal 2.15/s -- -8% -18% -38% tail 2.35/s 9% -- -11% -32% faster 2.64/s 23% 12% -- -24% loop 3.45/s 60% 47% 31% --

I put the caller thingee in there to ensure that the for loop didnt get optimized away. Which is in itself also a good argument for just using a loop in the first place.

---
$world=~s/war/peace/g


In reply to Re^2: Tail recursion using goto ⊂ (was: Re^3: Trinary Operator Semantics) by demerphq
in thread Trinary Operator Semantics by hardburn

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.