Yet another unpack trick

djberg96 on 2002-11-25T18:55:35

While going through John's code (free code review for John!), I came across this tidbit:

map(ord, split('', $word));

Well, Ruby doesn't have an 'ord()' function, so I used this instead:

word.unpack("c*")

At RubyConf 2002, I demonstrated that Perl's 'split()' function by itself is faster than 'unpack()' for splitting words up into chars. But I figured that a split + map combo would be slower. Naturally, I did a benchmark.

use strict; use Benchmark;

our $word = "Hello";

timethese(1000000,{ "unpack" => q{ unpack("c*",$word); }, "map n split" => q{ map(ord, split('', $word)); }, });

Benchmark: timing 1000000 iterations of map n split, unpack... map n split: 29 wallclock secs (26.92 usr + 0.00 sys = 26.92 CPU) @ 37147.10/s (n=1000000) unpack: 5 wallclock secs ( 4.17 usr + 0.00 sys = 4.17 CPU) @ 239808.15/s (n=1000000)

John's code only does this once per file IIRC, so no big deal. Just something to keep in mind. :)