At which n does binary search become faster than linear search on a modern CPU?

前端 未结 3 674
陌清茗
陌清茗 2020-12-16 11:41

Due to the wonders of branch prediction, a binary search can be slower than a linear search through an array of integers. On a typical desktop processor, how big does that a

3条回答
  •  庸人自扰
    2020-12-16 12:08

    Not many - but hard to say exactly without benchmarking it.

    Personally I'd tend to prefer the binary search, because in two years time, when someone else has quadrupled the size of your little array, you haven't lost much performance. Unless I knew very specifically that it's a bottleneck right now and I needed it to be as fast as possible, of course.

    Having said that, remember that there are hash tables too; you could ask a similar question about them vs. binary search.

提交回复
热议问题