Premature optimization means improving a program before testing whether it is fast enough or identifying a real performance problem. A solution that seems slow may already meet its needs, while a more sophisticated version can be harder to get right. section 9.5.1
Use this practical decision sequence:
- Try the simple implementation first. section 9.5.1
- Keep it if it is fast enough and completes the job. section 9.5.1
- Consider a faster solution only when the program is genuinely too slow or used often enough to justify extra effort. section 9.5.1
Comparing duplicate files
A Python script compares every pair of PNG files in a directory and may become slow for large directories. Rather than immediately replacing it, run it first and optimize only if its performance causes a real problem. section 9.5.1
```pythonimport osimport filecmp# Replace this with the actual directory path where your .png# files are locateddirectory = '/path/to/directory'# Iterate over all the files in the directoryfor filename1 in os.listdir(directory):if filename1.endswith('.png'):for filename2 in os.listdir(directory):if filename2.endswith('.png') and filename1 != filename2:file1 = os.path.join(directory, filename1)file2 = os.path.join(directory, filename2)if filecmp.cmp(file1, file2):print(f'{filename1} and {filename2} are duplicates.')```
Inspect the straightforward nested-loop implementation that illustrates a deliberately unoptimized starting point. section 9.5.1

