This is not a good way to do this. Instead of looping through all n labels once and storing the results for later, this code loops n * n times. For 2 labels, this is only 4 loops but for 500 labels it loops 250,000 times. In other words, instead of O(n) time complexity it's O(n^2).