开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜