In general, when you have questions like this the real answer is to try it. The Benchmark module is your friend:

use Benchmark qw/ cmpthese /; cmpthese(-5, { outside => q{ my $scalar; for (1..10_000) { $scalar = 1; } }, inside => q{ for (1..10_000) { my $scalar = 1; } }, });
gives me:
Rate inside outside inside 261/s -- -15% outside 307/s 18% --

I'm not sure why the 'outside' version is faster, and it intrigues me - but if all you care about is which is faster, you don't need to know.

Be careful about reading the percentages without noticing the rate though - since the assignment is happening 10,000 times for each iteration, we're talking about a 15% difference in speed for an operation that takes about a third of a microsecond. That is, you need to perform such an assignment about 18 million times before you can save 1 second by declaring the variable outside the loop. In most cases the clarity achieved by declaring the variable at the innermost scope far outweighs such microscopic savings.

Hugo


In reply to Re: Re: Re: Two Questions on "my" by hv
in thread Two Questions on "my" by C_T

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.