This offloads the work to the regex engine and is *much* faster:
sh-3.1$ perl benchmark.pl Rate split1 substr1 subst split1 5.05/s -- -82% -100% substr1 27.7/s 449% -- -99% subst 3551/s 70273% 12719% -- ok 1 ok 2 1..2
The function, could be done in-place which would be even faster:
sub subst { my ($s1, $s2) = @_; my $s3 = $s1; { use bytes; $s3 =~ s/(\0)/substr $s2, $+[0]-1, 1/eg; } $s3; }
The complete benchmark file (now with tests):
#!/usr/bin/perl use 5.6.0; use strict; use warnings FATAL => 'all'; use Benchmark qw( cmpthese ); use Test::More 'no_plan'; my $s1 = join '', (do_rand(1) x 100_000); my $s2 = join '', (do_rand(0) x 100_000); cmpthese( -2, { 'split1' => sub { my $s3 = split1( $s1, $s2 ) }, 'substr1' => sub { my $s3 = substr1( $s1, $s2 ) }, 'subst' => sub { my $s3 = subst($s1, $s2) }, }); my $s30 = split1( $s1, $s2 ); my $s31 = substr1( $s1, $s2 ); my $s32 = subst( $s1, $s2 ); is($s30, $s31); is($s31, $s32); sub split1 { my ($s1, $s2) = @_; my @s1 = split //, $s1; my @s2 = split //, $s2; foreach my $idx ( 0 .. $#s1 ) { if ( $s1[$idx] eq chr(0) ) { $s1[$idx] = $s2[$idx]; } } return join '', @s1; } sub substr1 { my ($s1, $s2) = @_; for my $idx ( 0 .. length($s1) ) { if ( substr($s1,$idx,1) eq chr(0) ) { substr($s1, $idx, 1) = substr($s2, $idx, 1); } } return $s1; } sub subst { my ($s1, $s2) = @_; my $s3 = $s1; { use bytes; $s3 =~ s/(\0)/substr $s2, $+[0]-1, 1/eg; } $s3; } # This makes sure that $s1 has chr(0)'s in it and $s2 does not. sub do_rand { my $n = (shift) ? int(rand(255)) : int(rand(254)) + 1; return chr( $n ); }

In reply to Re: Challenge: CPU-optimized byte-wise or-equals (for a meter of beer) by avar
in thread Challenge: CPU-optimized byte-wise or-equals (for a meter of beer) by dragonchild

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.