RoRvsWild Profile picture
Aug 23 1 tweets 2 min read Read on X
Array#find does not scale

Because scanning sequentially becomes linearly slower as the array grows. But looking for data through an ordered array is extremely fast!

Indeed, it allows to search via dichotomy. At each step it splits the array in half, then splits in half again and so on. It avoids scanning sequentially all entries. The complexity is less: O(log(n)) instead of O(n).

It's much faster. It's like an index. It's possible because data are sorted.

We are lucky because Ruby provides Array#bsearch. Let's compare it with Array#find against 1 million entries from 1 to 1_000_000.

123_456 is a little after the beginning of the array and 654_321 is a little after the half. To be fair we will look for both values and see the difference at the end.

See code in 1st image.

Bsearch is always a lot faster. It's impossible to tell of how much, because it depends of the size of the array and where is the data. Do not forget that the array must be sorted and the condition cannot change.

Moreover the execution time of bsearch does not vary too much. Whereas for Array#find(654321) is a lot slower than Array#find(123456) because the former is further in the array. That is why, Array#find does not scale 😉

Looking through an array of numbers is not real use case. Let's see how we can create an index for real data. Note that, as a database index, it's relevant only if you have more reads than writes.

See code in 2nd image.

#rubyonrails #highspeedrorImage
Image

• • •

Missing some Tweet in this thread? You can try to force a refresh
 

Keep Current with RoRvsWild

RoRvsWild Profile picture

Stay in touch and get notified when new unrolls are available from this author!

Read all threads

This Thread may be Removed Anytime!

PDF

Twitter may remove this content at anytime! Save it as PDF for later use!

Try unrolling a thread yourself!

how to unroll video
  1. Follow @ThreadReaderApp to mention us!

  2. From a Twitter thread mention us with a keyword "unroll"
@threadreaderapp unroll

Practice here first or read more on our help page!

Did Thread Reader help you today?

Support us! We are indie developers!


This site is made by just two indie developers on a laptop doing marketing, support and development! Read more about the story.

Become a Premium Member ($3/month or $30/year) and get exclusive features!

Become Premium

Don't want to be a Premium member but still want to support us?

Make a small donation by buying us coffee ($5) or help with server cost ($10)

Donate via Paypal

Or Donate anonymously using crypto!

Ethereum

0xfe58350B80634f60Fa6Dc149a72b4DFbc17D341E copy

Bitcoin

3ATGMxNzCUFzxpMCHL5sWSt4DVtS8UqXpi copy

Thank you for your support!

Follow Us!

:(