Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: chopping lots of characters

by hmerrill (Friar)
on Jun 24, 2004 at 12:12 UTC ( [id://369306]=note: print w/replies, xml ) Need Help??


in reply to chopping lots of characters

Yeah you can do that by calling chop 4 times, but that's 4 function calls. Without actually checking performance on this I would think(?) that one call to substring would be faster, but...
$string = substr($string, 0, -4);
that will give you $string containing all but the last 4 characters of what it started with.

HTH.

Replies are listed 'Best First'.
Re: chopping lots of characters
by Abigail-II (Bishop) on Jun 24, 2004 at 12:38 UTC
    A quicky test shows that 3-arg substr is faster than chop, but a 4-arg substr is even faster - and that's to be expected because it saves a copy. Differences aren't dramatic though.
    #!/usr/bin/perl use strict; use warnings; use Benchmark qw /cmpthese/; chomp (our @strings = <DATA>); cmpthese -5 => { chop => 'my @copy = @strings; foreach my $str (@copy) { chop $str; chop $str; chop $str; chop $str; }', substr3 => 'my @copy = @strings; foreach my $str (@copy) { $str = substr $str => 0, -4; }', substr4 => 'my @copy = @strings; foreach my $str (@copy) { substr $str => -4, 4 => ""; }', }; __DATA__ asdfjas;dfjas;dfjas;dkfjasdfasdf asd sdfajsd;flaks Rate chop substr3 substr4 chop 152166/s -- -11% -14% substr3 170187/s 12% -- -4% substr4 176800/s 16% 4% --

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (9)
As of 2024-04-18 08:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found