Often the fastest code is also the clearest and easiest to understand code. Sometimes this isn’t true though. When you measure the performance of different parts of your request and find something you can optimise you can end up with code that requires a lot of context to understand. Unless the optimisations are documented a future maintainer is going to have trouble knowing what changes they can safely make. Remember, that future maintainer could be you in six months time!

Document the approach, which parts of the code are critical to performance, and what the pre-conditions are for it to work. It’s also a good idea to keep the slow implementation around if you can so you can run it with the same input and check the output against the optimised version. This allows you to figure out if a bug is in the algorithm or the optimisation.

If you’re the maintainer and are having trouble trying to figure out the optimised code then doing the reverse and “un-optimising” the code temporarily can be a good way to figure out what it’s actually doing. If you do this then document as you go so you or the next person doesn’t have to figure it all out again.