My nested loops went from 40 minutes to 90 seconds and the fix was one misplaced line
Six months ago I started learning Python and built a little script that sorts my downloaded photos by date. It worked, but it took about 40 minutes to chew through 3,000 files, so I just set it and went to make dinner. Last weekend I finally sat down with a guy from my library's code meetup in Dayton and he spotted the problem in about two minutes: I had my folder scan loop inside my file loop instead of the other way around. After I swapped them the same 3,000 files ran in 90 seconds. I felt like an idiot for not seeing it, but also kind of amazed that one indentation level could cost me 38 minutes. Has anyone else had a bug that was mostly just your loops doing way more work than they needed to?
Nested loops are a sneaky trap. You think it's just one extra pass but it's actually files times folders, so 3,000 files scanning 3,000 times blows up fast. Same thing bit me with a CSV compare once, took forever until I moved the read outside the inner loop. Lesson learned the hard way.