Optimize get_mpi_datatype_impl to use arrays instead of vectors.

Also do not create new copies at each variable but use the same ones.
This makes the speed practically identical to a hand-written version.