- using Stopwatch
- avoid when possible: slicing, dynamic, exceptions, i/o
- don't optimize if you don't need to, root of all evil
From the discussion thread in the forums (Why so slow?), some modified versions of the code are available for comparison:
- With Python 3.6.0, running against a slightly modified version (for tracking time) with 50,000 loops yielded a run-time of 0.66819638 seconds.
- An initial port (which included substantial refactoring to identify the cause of the different final results) with 50,000 loops yielded a run-time of 98.284 seconds
- After numerous attempts at speed improvement, the cobra code was sped up to a run-time of 0.057 seconds (or 11x faster than python, or 1,724x faster than original implementation.
Some of the strategies attempting are listed below and whether they yielded much of a performance change:
- Made sure the the for loop variables had explicit types: yielded 33x improvement
- Used float instead of decimal: yielded 7x improvement
- Using multiplication instead of division: yielded 1.2x improvement
- Converted Math.pow to Math.sqrt for square roots: yielded 1.05x improvement
- Moved variable declarations into function-level scope: NO IMPROVEMENT
- Replaced properties with public fields: 1.6x improvement
Here are some select discussions on performance: