DEV Community

Discussion on: It's Ruby, There Must Be a Better Way

Collapse
 
curtisfenner profile image
Curtis Fenner • Edited

Because, each time we pop an item out, all of the items behind that item have to figure out what to do with the gap that it left.

You can fix this by swapping the element with the last element, and then popping off the last element, which is always cheap:

@@possible_names[next_index] = @@possible_names[-1]

# Drop off the last value. That's OK, because the last value just replaced
# the value-to-be-used-up.
@@possible_names.pop()

This only works because you don't actually care about the order of values in @@possible_names!

Another much more involved approach would be some kind of sparse Fenwick tree. That way, startup time is instantaneous, and you only use lots of memory when you've roughly used up every-other ID.

Collapse
 
rpalo profile image
Ryan Palo

Woah cool! I’ll look into that. Thanks for the ideas! 😃