Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby#index Method VS Binary Search

Given an element and an array, the Ruby#index method returns the position of the element in the array. I implemented my own index method using binary search expecting mine would outperform the built-in one. To my surprise, the built-in one ran approximately three times as fast as mine in an experiment.

Any Rubyist knows the reason why?

like image 899
Terry Li Avatar asked Sep 15 '11 19:09

Terry Li


People also ask

What does ruby symbolize?

The ruby has become a symbol of love and commitment. It was once thought to protect against misfortune and illness. Early cultures treasured the gem, believing that it held the power of life due to its color association with blood. It has also been thought to remedy bleeding and inflammation, and increase body warmth.

What is special about ruby?

Ruby gets its red coloring from trace amounts of chromium. Ruby measures 9 on the Mohs Scale of Hardness, second only to diamond and matched with sapphire. This makes ruby an extremely hard and durable gemstone.

Why are rubies so rare?

Rubies are one of the rarest gemstones. The rarest rubies come from Burma (Myanmar), due to their high quality and exceptional color. Good quality rubies larger than one carat are also extremely rare—and expensive.

How much is a ruby worth?

Rubies can run as little as $1 a carat to $100,000+ a carat, depending on the 4Cs. One of the most expensive rubies ever sold is the Sunrise Ruby, selling for over a million dollars a carat at 25 carats.


1 Answers

The built-in #index is not a binary search, it's just a simple iterative search. However, it is implemented in C rather than Ruby, so naturally it can be several orders of magnitude faster.

like image 120
wersimmon Avatar answered Sep 21 '22 03:09

wersimmon