开发者

Ruby#index Method VS Binary Search

开发者 https://www.devze.com 2023-04-05 17:35 出处:网络
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 outperf

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

精彩评论

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