by billybob · 15y ago · 0 comments
Originally, my logic was something like "for each checkbox that's checked or unchecked.... for each product that may or may not have that feature..." The nested for loop was fine with a small number of checkboxes and products, but as I got more products and more checkboxes, it began to slow down. My friend pointed out that it was Big O of N squared and explained what that meant. It was eye-opening.
I rewrote it to first compile a list of checked features (one pass through the checkboxes) and then show/hide the products (one pass through the products), which scales linearly.
I can't say that I think about Big O every time I write an algorithm, but I do have a sense that nested loops are dangerous.
If you had a form where the number of checkboxes scaled with the number of items on the list, then you might end up with an O(n^2) algorithm, depending on how exactly they scale.
My problem would have been N^N if I had been doing "for every checkbox... for every checkbox" instead of "for every checkbox... for every product..."
So it wasn't n^2, but it was scaling poorly.
The way I rewrote it, I had (Number of products) operations. So for 200 products, I had 200 operations.
You can see that this made it much more tenable to add 100 more products, even if it wasn't N^2.