Using 2-opt Heuristic in a Genetic Algorithm for TSP
One optimization to your pseudo-code is to calculate the new cost of a route after performing a 2-opt move by:

cost = cost - d[b(i)][i] - d[i][a(i)] - d[b(k)][k] - d[k][a(k)] + d[b(i)][k] + d[k][a(i)] + d[b(k)][i] + d[i][a(k)]


with $b(x), a(x)$ being the node before and after node $x$ on your current route.