How to avoid slow nested loops?
OP
The article's star map example with two loops is clear, but my real data has 10,000 × 10,000 items and it's crawling.
The article's star map example with two loops is clear, but my real data has 10,000 × 10,000 items and it's crawling.
Comments 5
Log in to join the discussion.
Log in Create account100 million iterations in pure Python will be slow no matter what. What are you actually doing inside the loops?
For each sensor ID in list A, I check if it's in list B.
Then you don't need nested loops at all. Convert B to a set once and check membership:
That's 10,000 fast lookups instead of 100 million comparisons.
From several minutes to under a second. Wow.
Classic. Nested loops for "find matches" are almost always replaceable by a set or dict.