in reply to Interleaving bytes in a string quickly


For the specific example of interleaving a null byte this should be ~50 times faster than the original solution:
$out = pack 'v*', unpack 'C*', $buf;

--
John.

Replies are listed 'Best First'.
Re^2: Interleaving bytes in a string quickly
by BrowserUk (Patriarch) on Feb 26, 2010 at 14:46 UTC

    Yes, that was an unfortunate choice of example. In the real thing, it isn't a null byte. Nice lateral thinking though!


    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.

      Then maybe something like this. It should still be ~25 faster than the original for the general case:
      sub interleave { my $str = shift; my $filler = 64; # Char number. my $hi_bytes = pack 'v*', unpack 'C*', $str; my $lo_bytes = pack 'n*', ($filler) x length $str; return $hi_bytes | $lo_bytes; }

      --
      John.

        this variation...
        $s = time; $out4 = (pack 'v*', unpack 'C*', $buf) | ("\x00$filler" x length $buf) +; print time() - $s, "\n";
        ... introduces very low overhead.