How to write complex code
I've been trying to write some complex code recently and have caused a lot of headaches for myself. The heart of almost all these issues is premature optimization.
Start with a working version - no matter how inefficient. This will help scaffold the chunks of logic for future development. This can also be used to develop interfaces for later rounds. It may also make sense to do profiling here if the base model is close to objective algorithm. Get tests in place around this version that can be reused for later versions.
Get a working version of the actual algorithm. Avoid anything done for optimization that is below the base O class of the algorithm. Use the interfaces here.
Profile and compare. Use profiling to eliminate bottlenecks. Make sure that the algorithm is at least in the same O class as a more general purpose algorithm.
Start optimizing. Simple optimizations can be made on the base version (object reuse). For complex (lists indexes replacing pointers) optimizations, make a copy and just implement it there. Benchmarks should justify the improvement. If the base version has a major improvement, it may be easier to rebuild the derived version that apply the changes to the derived version.