Hacker News new | ask | show | jobs
by riskable 698 days ago
I've seen memoization improve performance by enormous amounts. Even for simple functions that do a few simple calculations before returning a result.

Another go-to of mine is to take conditionals out of loops that really only need to be checked once. For example:

    for foo in whatever:
        for bar in foo:
            if len(foo) > some_value:
                do_something(bar)
Can become:

    for foo in whatever:
        if len(foo) > some_value:
            for bar in foo:
                do_something(bar)
This example is trivial and wouldn't gain much but imagine if `len(foo)` was a more computationally expensive function. You'd only need to call it on each iteration of foo instead of every iteration of foo * bar.
1 comments

I wouldn't even really call that loop example an "optimization", it is just the obviously more efficient implementation.
Yet I see it constantly. That pattern of `for foo in whatever: for bar in foo` is everywhere. People don't even think about it... They just write the looping part then start thinking about the logic below. It's such a common thing I'm surprised compilers and interpreters don't just optimize it away :shrug: