Here you go:
#!/usr/bin/env perl use strict; use warnings; use Inline C => <<'__EOI__'; /* sv_in and sv_pad may not be NULL */ /* That won't happen when called from Perl */ SV* interleave_bytes(SV* sv_in, SV* sv_pad) { STRLEN l_in; char* p_in = SvPVbyte(sv_in, l_in); STRLEN l_pad; char* p_pad = SvPVbyte(sv_pad, l_pad); char pad; SV* sv_out; char* p_out; if (l_pad != 1) croak("usage"); pad = *p_pad; sv_out = newSVpvn("", 0); p_out = SvGROW(sv_out, l_in*2+1); /* XXX Could overflow */ SvCUR_set(sv_out, l_in*2); while (l_in--) { *(p_out++) = *(p_in++); *(p_out++) = pad; } *p_out = '\0'; return sv_out; } __EOI__ use Time::HiRes qw( time ); my $buf = chr(1) x 1e6;; my $s = time; my $out = interleave_bytes( $buf, chr(0) ); print time() - $s, "\n"; #use Devel::Peek; #Dump $out; $buf = chr(1) x 1e6;; $s = time; $out = join( chr(0), unpack '(A1)*', $buf ) .chr(0); print time() - $s, "\n";
0.00459790229797363 0.446739912033081

Update: Fixed bugs mentioned elsewhere in thread.


In reply to Re^2: Interleaving bytes in a string quickly by ikegami
in thread Interleaving bytes in a string quickly by BrowserUk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.