Revert to speed-optimized version as space-optimized turned out to be slower