Hmmm time to get out the special can-o-worms tin opener.
Isn't there always time for another discussion
about (premature) optimization and the many ways in which
honest but unwary programmers may be misled by benchmarks? :)
Scratch that. It's been done too many time before. The
question "Which is faster, X or Y?" is badly formed, and
particularly silly (sorry, but it is) when it comes to
tr/// vs s/// for a one character
substitution.
The question should always be "Which fits best in this particular
place in my program?" The latter question is
much more to the point.
In most cases the time difference will be negligible.
Do not be overly concerned about fine-tuning Perl programs
for execution speed. You will end up sacrificing your time
and the clarity of your code
for little tangible reward. | [reply] [d/l] [select] |
I agree, the proper question is "which is better in my program". Speed may be one of several concerns.
| [reply] |
In most situations I would agree.... However, in this case the problem space was clearly defined and the question is a valid one in my opinion. The question was something like:
"I want to replace all occurances of '.' with '/' in a string. I know that there are at least two ways to do this (s/// and tr///). Which one is faster?"
Now perhaps one could argue that "faster" should be replaced with something a bit more encompassing (better, 'the right choice', etc), but in the end what really is the difference between s|\.|/|g and tr|\.|/|?
What if the question had been:
"I'd like to grab the last character in a string. I know there are at least two ways to do this (split '',$txt)[-1] and substr($txt,-1). Which one is faster?"
Would it still be considered premature optimization to
suggest that substr is the correct answer?
In both questions there is a solution that uses a slower general tool (regex, split) and one with a faster specialized tool (tr///, substr). If you aren't going to use the specialized tools in these cases, when are you *ever* going to use them?
Oh, and I posted some benchmarks a while back showing tr/// running about 15 times faster that s/// for
a particular case...
Update: virtualsue has brought to my attention that her "premature optimization" statement was about running benchmarks for small insignificant parts of a program. She wasn't advocating s/// over tr/// in this case, simply stating that benchmarking the two was a poor use of human cycles. To that I wholehartedly agree...
I seem to have read the node slightly out of context,
and get a little touchy when I see people using elephant guns (s///) when a well designed flyswatter (tr///) would do.
-Blake
| [reply] [d/l] [select] |