Performance gain from moving portfolio out of inner loop

#239 with commits not related to portfolio picked out.