开发者

Efficiency of Searching an Array Vs Searching in Text.... Which is Better?

I have a List of (integer)ID's, which i am storing as text, like

开发者_运维知识库
23;45;67;12;332;783;123;33;15;87;41;422;88;58;

now i am working with PHP, i want to check if a particular ID already exists in that TEXT, i have the explode function, which can give me an array of numbers, and then i can use the in_array function, alternatively i can just use the strpos function to find in text.

so which one will be more efficient accourding to you ?

Thanks a lot for taking time to read this.


If all you have to do is look up a single ID, then strpos() will be more efficient, because all it has to do is find an occurrence of id;, whereas explode() will do a lot more than that, not to mention the costly call to in_array().


strpos() is pretty fast. However, if you combine explode() and array_flip, you get an array where all the keys are your ids, and you can just use isset($keys[$id]). This is gonna be faster since it's a direct lookup in a hash-table, but the explode + array_flip are costly, so it's only worth it if you do many lookups in the same data during one request.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜