in reply to Re: bin2dec for big numbers
in thread bin2dec for big numbers

Thanks for the insightful reply.

reduce definitely makes the code much clearer. I wonder how it is in terms of performance versus the bare loop.

I wholeheartedly agree with the variable name change you are proposing. has_overflown makes the code clearer.

Regarding changing the for loop with index to one w/o an index but on reverse, I just have a performance concern. reverse probably takes linear time in string length, and with an explicit for loop that goes from the end of the string to its beginning the cost is saved.

Also, in your proposed implementation of mul2 with join reverse map I'm not sure if it's indeed clearer than the for loop. Again, the issue of performance rises, since you have two reverses extra.

Replies are listed 'Best First'.
Re^3: bin2dec for big numbers
by Aristotle (Chancellor) on Jan 18, 2005 at 13:13 UTC

    ObCounter: if you're so concerned about speed, why are you doing numerics in Perl? :-) In case of the reverse join, I don't see why your code is better anyway: you are constantly replacing the string by a character+string.

    In any case, it could probably be sped up a little by using string reverse vs list reverse:

    sub mul2 { my ( $str, $have_overflow ) = @_; my $ret = reverse join '', map { my $c = $_ * 2 + ( $have_overflow ? 1 : 0 ); $have_overflow = ( $c >= 10 ); ( $c % 10 ); } split //, scalar reverse $str; ( $have_overflow ? 1 : '' ) . $ret; }

    Makeshifts last the longest.