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?
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.
来源:https://stackoverflow.com/questions/7436155/rubyindex-method-vs-binary-search