• sugar_in_your_tea@sh.itjust.works
    link
    fedilink
    English
    arrow-up
    6
    ·
    edit-2
    3 days ago

    Yes, Python is the wrong choice if performance is your top priority.

    But here’s another perspective: why leave easy performance wins on the table? Especially if the cost is simpler code that works as you probably wanted anyway with both None and []?

    Python is great if you want a really fast development cycle, because the code is generally quite simple and it’s “fast enough.” Any wins for “fast enough” is appreciated, because it delays me needing to actually look into little performance issues. It’s pretty easy for me to write a simple regex to fix this cose (s/if len\((\w+)\) == 0:/if not \1:/), and my codebase will be slightly faster. That’s awesome! I could even write up a quick pylint or ruff rule to catch these cases for developers going forward (if there isn’t one already).

    If I’m actively tweaking things in my Python code to get a little better performance, you’re right, I should probably just use something else (writing a native module is probably a better use of time). But the author isn’t arguing that you should do that, just that, in this case, if not foo is preferred over if len(foo) == 0 for technical reasons, and I’ll add that it makes a ton of sense for readability reasons as well.

    Here are some other simple wins:

    • [] and {} instead of list() and dict() - the former copy constants, whereas the latter actually constructs things; oh, and you save a few chars
    • use list comprehensions instead of regular loops - list comprehensions seem to be faster due to not needing to call append (and less code)
    • use built-ins when you can - they’re often implemented in native code

    I consider each of those cleaner Python code anyway, because they’re less code, just as explicit, and use built-in language features instead of reinventing the wheel.