⚡️ Speed up method Colors.hex2rgb by 89%
#12
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
📄 89% (0.89x) speedup for
Colors.hex2rgbinultralytics/utils/plotting.py⏱️ Runtime :
1.62 milliseconds→859 microseconds(best of76runs)📝 Explanation and details
The optimized code achieves an 88% speedup by eliminating Python generator expression overhead in the
hex2rgbfunction and streamlining the palette initialization.Key optimizations:
Removed generator expression overhead: The original
hex2rgbusedtuple(int(h[1 + i : 1 + i + 2], 16) for i in (0, 2, 4))which creates a generator, iterates through it, and converts to tuple. The optimized version uses direct tuple construction(int(h[1:3], 16), int(h[3:5], 16), int(h[5:7], 16)), eliminating the generator overhead and reducing function call complexity.Inlined palette conversion: During
Colors.__init__(), instead of callingself.hex2rgb()for each color, the optimized version directly performs the hex-to-RGB conversion inline:(int(c[0:2], 16), int(c[2:4], 16), int(c[4:6], 16)). This removes 20 function calls during initialization.Why this speeds up execution:
__next__()callstuple()conversionhex2rgbexecutes in 2.66ms vs 4.82ms for the original (45% faster)Performance characteristics:
The optimizations are most effective for:
Colorsobject creation (benefits from faster initialization)hex2rgbcalls (benefits from direct tuple construction)The optimized version maintains identical functionality and error handling while delivering substantial performance gains through reduced Python interpreter overhead.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-Colors.hex2rgb-mi8eaffqand push.