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

≡放荡痞女 提交于 2020-01-11 10:35:09

问题


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.


回答1:


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().




回答2:


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.



来源:https://stackoverflow.com/questions/6325128/efficiency-of-searching-an-array-vs-searching-in-text-which-is-better

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!