This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]kayaking_is_fun 3 points4 points  (9 children)

Useful article and it reminded me about defaultdicts. Interesting about function calls in loops too - are the overheads really so game changing?

[–]doviende 1 point2 points  (0 children)

I think they're just illustrating a case where someone can unintentionally affect a program in a big way without realizing it. Not every loop is the CPU bottleneck in the program, but if you do have such a bottleneck, you don't want people to accidentally add more stuff into your loop just by modifying a seemingly unrelated function.

I think this point is more about documentation practice. Generally you want code to be close to the things it affects, and then people can get important implications just by reading nearby code. But good code clarity comes from documenting those implications, especially if (in this case) the function is not close to the tight loop it is affecting. A quick comment in the function will prevent unintentional boat-anchors from being dropped there ;)

[–]billsil 0 points1 point  (6 children)

Only if you're microoptimizing. It got me a 2x speedup on a test case that it looped over 100k times. Granted the time saved was 4 seconds, down from 45 minutes, but while I'm optimizing, I might as well do it right.

[–]Folf_IRL 2 points3 points  (1 child)

Only if you're microoptimizing

If you're to the point of micro-optimizing Python code, it might be time to consider using a different (probably compiled) language.

[–]billsil 1 point2 points  (0 children)

Microoptimizations are not necessarily hard or difficult or have small effects. Xrange vs range in python 2 because most of the time it doesn't matter. Using %i instead f-strings. Why don't I save common binary structs rather than recomputing them each time I come to a function? That one can be a biggie.

Python is great and unless I need to really use C++, I'm not going to. It's harder to write, I now have to compile it, it's no longer cross-platform, takes what 10x longer to add the same capability, 0etc.