T
21

Found out that Python's pass statement actually costs CPU cycles in a tight loop

I was profiling some code last weekend and saw a 12% speedup just by replacing 500 'pass' placeholders with a comment instead, has anyone else seen a performance hit from dummy statements like that?
3 comments

Log in to join the discussion

Log In
3 Comments
terry_wood51
Makes sense, Python's interpreter still parses and executes that no-op every time.
2
margaret_jackson73
margaret_jackson7327d agoMost Upvoted
Exactly. That no-op still adds overhead even if it does nothing. Every loop iteration has to parse and execute that line, so the time adds up fast. Its the kind of micro-optimization that beginners ignore but can really matter in tight loops. Ive seen people use those as placeholders and wonder why their code runs slow. Python is already slow, so adding extra work just makes it worse. If you really need a placeholder, at least use a comment instead of a no-op. Best advice is to just leave the loop body empty if you don't need anything there. Save the no-op for debugging only.
1
laura_black31
laura_black3124d agoMost Upvoted
Honestly I've done the same thing with those placeholder passes. Switched to just leaving the loop body empty with a comment and saw a small but noticeable speed bump in a data processing script. It adds up way more than you'd think.
5