Well, you cannot compare a simple operation such as the sum of 2 Ints with a union operation of 2 sets. I expect that the performance of these operations will be very different, especially if your sets contain a lot of elements.
You do not need an alliance because you are already intersecting. Try the following:
def grade: Double = { val setA: HashSet = // get from somewhere else val setB: HashSet = // get from somewhere else if ((setA size) == 0 || (setB size) == 0) return 0 else { val inter = setA & setB size return inter / ((setA size) + (setB size) - inter) } }
However, I find your measurement a bit strange, because I expected both operations (union and intersection) to take about the same O (n) time. Removing a connection should improve performance by half (2 s) ...
source share