Multiplication optimization

Paul McGuire ptmcg at austin.rr.com
Sat Feb 18 19:48:38 EST 2006


Does Python's run-time do any optimization of multiplication
operations, like it does for boolean short-cutting?  That is, for a
product a*b, is there any shortcutting of (potentially expensive)
multiplication operations as in:

    if a == 0
        return 0
    if a == 1
        return b
    return a*b

Of course, for the cases where a is not 0 or 1 we are adding two
comparisons to each multiply operation.  But in some applications
(sparse matrices? binary conversion?), the multiplication step could be
avoided in many cases, if the user was aware that left-to-right
short-cutting were implemented.

Or by adding two *more* comparisons, then all multiplications would be
"optimized":

    if a == 0 or b == 0
        return 0
    if a == 1
        return b
    if b == 1
        return a
    return a*b

But this seems overkill, especially since boolean short-cutting only
works left-to-right.

Just curious...

-- Paul




More information about the Python-list mailing list