Optimize doctest generation. Closes #1226
Merge pull request #1233 from alco/1226-doctest-perf

Optimize doctest generation. Closes #1226