in reply to Using the third arguement for split
in thread is split optimized?
But you used it in an incorrect way. If the third argument is 1, it's effectively a noop. The third argument does not mean to discard everything after the first field.
my ($y) = split " ", "a b", 1;
print $y;
will print a b, and not a.
If you want to use only the first field, and use a third argument, just use:
my ($y) = split " ", $string, 2;
That's right. No indexing required. But even the limit isn't
required. Just the simple:
my ($y) = split " ", $string;
will do. And because it is so simple, Perl can optimize that.
Here's a benchmark program (there are brackets where indexing
is used - for some reason, perlmonks strip them), and the
results:
#!/opt/perl/bin/perl -w
use strict;
use Benchmark;
my $str = "a " x 6;
timethese -100 => {
index => sub {my ($y) = (split " " => $str) [0]},
regex => sub {my ($y) = $str =~ /(\S+)/},
limit => sub {my ($y) = (split " " => $str, 2) [0]},
plain => sub {my ($y) = split " " => $str},
}
__END__
Benchmark: running index, limit, plain, regex, each for at least 100 CPU seconds...
index: 125 wallclock secs (105.53 usr + 0.00 sys = 105.53 CPU) @ 34487.35/s (n=3639450)
regex: 121 wallclock secs (105.06 usr + 0.00 sys = 105.06 CPU) @ 43695.61/s (n=4590661)
limit: 123 wallclock secs (104.03 usr + 0.02 sys = 104.05 CPU) @ 48699.04/s (n=5067135)
plain: 120 wallclock secs (105.18 usr + 0.02 sys = 105.20 CPU) @ 52044.32/s (n=5475062)
The bottom line is, if you want Perl to do the optimizing, keep your code simple.
-- Abigail
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Brackets
by DrManhattan (Chaplain) on Jul 14, 2000 at 18:20 UTC | |
by Abigail (Deacon) on Jul 15, 2000 at 00:18 UTC | |
|
More benchmarks and stuff
by gryng (Hermit) on Jul 14, 2000 at 18:18 UTC | |
by Abigail (Deacon) on Jul 15, 2000 at 00:15 UTC | |
by gryng (Hermit) on Jul 15, 2000 at 02:25 UTC |