in reply to Re^2: Interesting unary - oddity
in thread Interesting unary - oddity

One possible explanation is that this implementation is mathematically equivalent to stripping the minus sign, but doesn't require changing the length of the string, which is somewhat faster. In C, switching the sign requires a single character write, while removing it requires making a new copy of the string that's one character shorter; even in Perl using substr, it's somewhat faster:
#!/usr/bin/perl use Benchmark; sub switchsign { if (substr($_[0],0,1) eq '-') { substr($_[0],0,1)='+'; } elsif (substr($_[0],0,1) eq '+') { substr($_[0],0,1)='-'; } else { substr($_[0],0,0)='-'; } } sub unsign { if (substr($_[0],0,1) eq '-') { substr($_[0],0,1)=''; } elsif (substr($_[0],0,1) eq '+') { substr($_[0],0,1)='-'; } else { substr($_[0],0,0)='-'; } } use constant X => '-'.'99999'; timethese(100_000, { switchsign => sub { my $a = X; switchsign($a) }, unsign => sub { my $a = X; unsign($a) }, });
Benchmark: timing 100000 iterations of switchsign, unsign... switchsign: 4 wallclock secs ( 1.37 usr + 0.00 sys = 1.37 CPU) @ 72992.70/s (n=100000) unsign: 4 wallclock secs ( 1.51 usr + 0.00 sys = 1.51 CPU) @ 66225.17/s (n=100000)