in reply to Re: Regex to take an ip address before a comma
in thread Regex to take an ip address before a comma

I think the split() solution is more efficient than the regex solution.

Tested with Perl 5.8.8 (ActiveState on WinXP)

#!/usr/bin/perl use strict; use warnings; use Benchmark qw( cmpthese ); my $str = ( ('X'x15) . ',' ) x 3; cmpthese( -1, { # using regex 's///' => sub { my ( $first ) = $str =~ m/(.*?),/; }, # using split without limit 'split_unl' => sub { my ( $first ) = split( m/,/, $str ); }, # using split with limit 'split_lim' => sub { my ( $first ) = split( m/,/, $str, 2 ); }, # using split with limit and slice for scalar assignment 'split_lim_sca' => sub { my $first = ( split( m/,/, $str, 2 ) )[0]; }, } )

my result:

Rate s/// split_lim split_unl split +_lim_sca s/// 577066/s -- -13% -13% + -15% split_lim 663032/s 15% -- -0% + -2% split_unl 663629/s 15% 0% -- + -2% split_lim_sca 679348/s 18% 2% 2% + --

Or did I miss something?

Replies are listed 'Best First'.
Re^3: Regex to take an ip address before a comma
by linuxer (Curate) on Nov 25, 2008 at 16:43 UTC

    and here's my result with a perl 5.10 (cygwin on same WinXP)

    Rate s/// split_lim split_unl split +_lim_sca s/// 288797/s -- -12% -12% + -15% split_lim 326805/s 13% -- -1% + -4% split_unl 330050/s 14% 1% -- + -3% split_lim_sca 339541/s 18% 4% 3% + --
      How can split which uses a regexp be faster than just a regexp? weird
        why not? It's a different regex after all. .*?, has to check all items prior to the comma because \n isn't allowed there, whereas as simple search for , doesn't have to do this work.