Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: The speed of $_ versus a lexical

by ariels (Curate)
on Jul 19, 2001 at 14:14 UTC ( [id://98022]=note: print w/replies, xml ) Need Help??


in reply to The speed of $_ versus a lexical

Your code is IO bound (most of the work goes to reading and writing, and even if the file is in memory you have to convert strings to numbers, etc.). Of course you're not going to see any difference between my and implicit operators.

Try this:

#!/usr/local/bin/perl -w use strict; use Benchmark; timethese(-2, { default => sub { $_="the quick brown fox"; s/brown/black/ }, my => sub { my $x="the quick brown fox"; $x =~ s/brown/black/ } });
I get a 2% speed difference; localising $_ makes the `my' version 4% faster.

Duplicating the string 10_000 times and performing global substitution makes the `my' version 11% faster.

Replies are listed 'Best First'.
Re:x2 The speed of $_ versus a lexical
by grinder (Bishop) on Jul 19, 2001 at 14:58 UTC
    duh! ok, so I changed the code to the following (by the way, am I the only one interested in playing around with Inline)? :

    #! /usr/bin/perl -w use strict; use Benchmark; my @a = (1..500000); use Inline C => <<'ADDUP_END'; double addup( SV* stub, ... ) { double total = 0; int i; Inline_Stack_Vars; for( i = 0; i < Inline_Stack_Items; ++i ) { total += SvNV(Inline_Stack_Item(i)); } return total; } ADDUP_END timethese shift || 100, { '$_' => sub { my $count = 0; foreach( @a ) { $count += $_; } }, 'my' => sub { my $count = 0; foreach my $var( @a ) { $count += $var; } }, 'Inline' => sub { my $count = addup( @a ); }, };

    now I see around a 7% gain in favour of lexicals (i.e., barely above the noise level). It's not the 25% I was expecting. Heh, the Inline method is close to an order of magnitude faster!

    update: tip o' the hat to Hofmator for spotting an orphan $rec.

    update 2001-08-06: in my travels through the older nodes in the monastery, I encountered another thread that deals with a similar topic: is 'my' that much faster than 'local'?. It may be of interest.

    --
    g r i n d e r

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://98022]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (3)
As of 2024-04-19 22:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found