in reply to Challenge: CPU-optimized byte-wise or-equals (for a meter of beer)
You picked the wrong one. moritz'es solution is broken. Its easy to be fast if you don't have to be correct. :-) (Hint: what happens if the first character in the string is \0?)
Seriously if you need to do this then use one of the XS variants. It will be fastest, however proving that it is might be difficult, especially when working with such large strings. Certainly I wouldnt trust Benchmark.pm with the inline modification variants, especially not the XS ones.
sub moritz { my ($s1, $s2) = @_; my $pos = 0; while ( 0 < ( $pos = index $$s1, "\000", $pos ) ) { substr( $$s1, $pos, 1 ) = substr( $$s2, $pos, 1 ); } } my $s1="\0x\0z"; my $s2="ABCD"; moritz(\$s1,\$s2); print $s1 ne 'AxCz' && 'not ','ok';
The code would be correct if it was
sub moritz { my ($s1, $s2) = @_; my $pos = 0; while ( -1 < ( $pos = index $$s1, "\000", $pos ) ) { substr( $$s1, $pos, 1 ) = substr( $$s2, $pos, 1 ); } }
But then its possible the benchmark results would change as the original isnt doing *anything* on a string that starts with "\0"
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Challenge: CPU-optimized byte-wise or-equals (for a meter of beer)
by kyle (Abbot) on Sep 12, 2007 at 18:41 UTC | |
by demerphq (Chancellor) on Sep 12, 2007 at 18:56 UTC |