48
loading...
This website collects cookies to deliver better user experience
for group in groups
for user in users
# do something with the group and user
end
end
100 * 100 = 10000
iterationssquared
time complexity, or O(n²)
, because 100 * 100 = 100²
. O(n²)
squared, we can work to reduce to O(n)
linear or O(log(n))
in most cases, which would make our algorithm to perform faster. 100²
:groups = [1, 2, ....100]
users = [1, 2, ....100]
for group in groups
for user in users
...
for group in groups
# do something with group and user
# now we are missing the user, but we need to fetch the user information from another data structure
end
O(n)
O(1)
, we can use a hash table. O(1)
. Example:users_idx = {}
for user in users
users_idx[user[:id]] = ...
end
users_idx
and the respective keys. users_idx = {}
for user in users
users_idx[user[:group_id]] = ...
end
for group in groups
user_information = users_idx[group[:id]]
# do something with group AND user information
end
O(n²)
? Let's compare it.100 * 100 = 10.000
iterations, whereas the second performs 100 iterations for building the index plus 100 iterations for iterating over groups, 100 + 100 = 200
. Put simply:nested loop: 100 * 100 = 10.000
index AND loop: 100 + 100 = 200
10.000
. We could write even more loops, three, four, five times. It doesn't matter, it will be linear O(n)
, because in terms of time complexity, O(n) = O(2n) = O(3n)
and so on...10 groups | 10 users => 2x faster
100 groups | 100 users => 3x faster
100 groups | 100 users => 31x faster
1000 groups | 1000 users => 70x faster
5000 groups | 5000 users => 510x faster