in reply to Challenge: CPU-optimized byte-wise or-equals (for a meter of beer)
I have a couple of solutions derived from the work of moritz and avar that show some inconsistency.
Update: The specific solutions below are incorrect, as dragonchild and ikegami have pointed out to me. The advice about times varying still applies.
In case anyone else wants to try my slight changes:
sub mrm_1 { my ( $s1, $s2 ) = @_; use bytes; my $pos = 0; while (-1 < ( $pos = index $$s1, '\0', $pos ) ) { substr( $$s1, $pos, 1 ) = substr( $s2, $pos, 1 ); } } sub mrm_3 { my ( $s1, $s2 ) = @_; use bytes; my @zeros = (); my $pos = 0; while ( -1 < ( $pos = index $$s1, '\0', $pos ) ) { push @zeros, $pos; } for ( @zeros ) { substr( $$s1, $_, 1 ) = substr( $s2, $_, 1 ); } }
Interestingly, building the extra loop of indexes in mrm_3 is within the margin of benchmarking error at least on some perls. Sometimes it beats mrm_1 and sometimes it doesn't. At least once on my Linux box they tied (exactly 1393/s each). mrm_2 is about mid-way through the results, so I didn't bother to show it.
Perhaps more interesting is that Corion's code works for me most of the time, but sometimes tries to perform a substr() outside the string. I haven't tried to figure out exactly why. That goes to show the debugging price for being too clever.
Update: fixed the index() error that demerphq points out above. The results seem to be coming up about the same. I'm guessing the chances of the test data have '\0' at index 0 hadn't bit very hard yet.
Update 2: changed a comparison of the ranges between ActiveState's perl and perl on the Linux machine to state so. It did refer incorrectly to Strawberry.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Challenge: CPU-optimized byte-wise or-equals (for a meter of beer)
by mr_mischief (Monsignor) on Sep 13, 2007 at 02:19 UTC |