This site is now 100% read-only, and retired.

XML logo

Perl needs a trim function
Posted by simonw on Wed 24 Apr 2013 at 17:21
Merely to stop the question being asked again and again.

NYTPROF claims that we have a bottleneck on 's/^\s*|\s*$//g' (I'll believe it when I see it run faster), google knows what to do, on our hardware the two line version below is ~50 times faster.

$x =~ s/^\s+//;
$x =~ s/\s+$//;

String::Util::trim() is only ~35 times faster than the single regular expression but has the advantage of readability, those who prefer code not to look like line noise will find comfort here.



Comments on this Entry

Re: Perl needs a trim function
Posted by Steve (90.193.xx.xx) on Wed 24 Apr 2013 at 23:04
[ View Weblogs ]

FWIW I always use the "slow" version:

$str =~ s/^\s+|\s+$//g;

Sure there might be faster versions, but that's simple and readable. I expect if trimming strings is ever a bottleneck I've got more serious problems.


[ Parent ]

Re: Perl needs a trim function
Posted by simonw (84.45.xx.xx) on Thu 25 Apr 2013 at 18:48
[ View Weblogs ]
This code had other issues as well. But the trim was called (indirectly) by a recursive function that iterates over the document tree it is fed, and I was feeding it a succession of documents. The actual usage is I suspect redundant most of the time, but I just needed it out of my NYTprof top spot.

I was just surprised at the performance hit of what is fairly common idiom, guess the lesson is as always use the library calls for doing common tasks as they encode wisdom I, and in this case my predecessor, don't have.

[ Parent ]