Note that there are some explanatory texts on larger screens.

plurals
  1. POIs Perl's unpack() ever faster than substr()?
    primarykey
    data
    text
    <p>Several times I've read that <code>unpack()</code> is faster than <code>substr()</code>, especially as the number of substrings increases. However, this benchmark suggests otherwise. Is my benchmark flawed, or is the alleged performance advantage of <code>unpack()</code> a holdover from older versions of Perl?</p> <pre><code>use strict; use warnings; use Benchmark; my ($data, $format_string, $n_substrings); my %methods = ( unpack =&gt; sub { return unpack $format_string, $data }, substr =&gt; sub { return map {substr $data, $_, 1} 0 .. $n_substrings - 1 }, ); for my $exp (1 .. 5){ $n_substrings = 10 ** $exp; print $n_substrings, "\n"; $format_string = 'a1' x $n_substrings; $data = 9 x $n_substrings; Benchmark::cmpthese -2, \%methods; } </code></pre> <p>Output (on Windows):</p> <pre><code>10 Rate unpack substr unpack 131588/s -- -52% substr 276802/s 110% -- 100 Rate unpack substr unpack 13660/s -- -57% substr 31636/s 132% -- 1000 Rate unpack substr unpack 1027/s -- -68% substr 3166/s 208% -- 10000 Rate unpack substr unpack 84.4/s -- -74% substr 322/s 281% -- 100000 Rate unpack substr unpack 5.46/s -- -82% substr 30.1/s 452% -- </code></pre> <p>As pointed out in some answers, <code>unpack()</code> does poorly on Windows. Here's the output on a solaris machine -- not nearly so decisive, but <code>substr()</code> still wins the foot race:</p> <pre><code>10 Rate unpack substr unpack 202274/s -- -4% substr 210818/s 4% -- 100 Rate unpack substr unpack 22015/s -- -9% substr 24322/s 10% -- 1000 Rate unpack substr unpack 2259/s -- -9% substr 2481/s 10% -- 10000 Rate unpack substr unpack 225/s -- -9% substr 247/s 9% -- 100000 Rate unpack substr unpack 22.0/s -- -10% substr 24.4/s 11% -- </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload