Yes, that's the precalculation part that takes the longest but only has to be done once. You don't code it the way you have it though, it's not solved by simply looping over all the nodes.