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 usi开发者_开发问答ng 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?
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.
精彩评论