Several times I\'ve read that unpack() is faster than substr(), especially as the number of substrings increases. However, this benchmark suggests
I get similar results to the questioner under Ubuntu 9:
This is perl, v5.10.0 built for i486-linux-gnu-thread-multi
10
Rate unpack substr
unpack 535925/s -- -3%
substr 552749/s 3% --
100
Rate unpack substr
unpack 57957/s -- -5%
substr 61264/s 6% --
1000
Rate unpack substr
unpack 4716/s -- -22%
substr 6075/s 29% --
10000
Rate unpack substr
unpack 466/s -- -24%
substr 609/s 31% --
100000
Rate unpack substr
unpack 46.3/s -- -23%
substr 60.5/s 31% --
But I'm not sure this is relevant. I don't tend to use unpack for simple string extractions, due to its unholy format string :-)
I think where it would shine is extracting encoded integers and all sorts of other binary information which is where I would use it.
One thing you should take from Matthew's and my (and your) benchmarks is that it will depend a lot on environmental factors. And keep in mind that speed, while good, is not the be-all and end-all - I don't think I've written much code that would be seriously affected by only being able to perform 4.6 million extractions per second rather than 6 million :-) You may need that extra performance but I doubt it for most applications written in Perl.