首页 > 编程语言 >php in_array 遍历,in_array大数组查询性能问题

php in_array 遍历,in_array大数组查询性能问题

时间:2023-01-31 15:55:15浏览次数:66  
标签:遍历 数组 numbering 查询 PHP key array php

问题

最近在实现一个项目接口的时候发现当数组过大的时候,数据返回的速度有点慢。接口数据返回最长反应时间2s,经过反复调试发现代码段耗时最长的部分在in_array()函数。

解决过程

在stackoverflow找到了一篇提供我解决思路的文章

- which is faster, array_key_exists or array_search?

文中说到:array_key_exists is much faster. array_search must traverse the whole array, so it is O(n). array_key_exists is a hash table lookup, so it is O(1).

----分割线----I think it’s faster for PHP to check for keys (array_key_exists() or simply isset($array[$key])). To search for a value, PHP must cycle through the array; to search for a key PHP will use a hash function.

该数组是用来保存用户账号,一直不销毁存储在内存。

原数组

$array=array('account1','account2','$account3');

修改后的数组

$array=array('account1'=>0,'account2'=>0,'$account3'=>0)

使用isset($array[$account])) 来检测账号是否存在该数组内

总结

由于in_array()函数对数组进行遍历查询,O(n),随n(数组长度)的增大耗时将增加。所以在对大数组使用in_array()函数应考虑效率问题。当面对大数组查询的时候,在PHP中应该尽量采用key查询而不是value查询。').addClass('pre-numbering').hide();

$(this).addClass('has-numbering').parent().append($numbering);

for (i = 1; i <= lines; i++) {

$numbering.append($('

').text(i));

};

$numbering.fadeIn(1700);

});

});

以上就介绍了in_array大数组查询性能问题,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

标签:遍历,数组,numbering,查询,PHP,key,array,php
From: https://www.cnblogs.com/minch/p/17079442.html

相关文章

  • PHPMyWind编辑器支持PowerPoint上传
    ​ 1.编辑器修改(可选)1.1在 ueditor/config.json 中添加代码块    /* 上传word配置 */    "wordActionName":"wordupload",/* 执行上传视频的action......
  • p57 Arrays 类,冒泡排序
    Arrays类数组的工具类java.util.Arraysutil--工具包由于数组对象本身并没有什么方法可以供我们调用,但API中提供了一个工具类Arrays供我们使用,从而可以对数据对象进行......
  • 图的遍历
    n=0N=10000all=0go=[0]*Nhd=[0]*Nnxt=[0]*Ndefadd_(x,y):globalallall+=1nxt[all]=hd[int(x)]go[all]=yhd[x]=alldefdfs(x):p......
  • Redis 遍历指定格式的所有key
        Redis作为当前最流行的内存型NoSQL数据库,被许多公司所使用,我们在实际使用中一般都会为key带上指定的前缀或者其他定义的格式,那么我们怎样能取出符合条件......
  • phpstorm xdebug设置
    填写上配置的url地址即可,端口如果不是80就自己填写为自己设置的端口最后打开顶部调试模式startlisiteningforphpdebug设置断点访问地址添加上?XDEBUG_SESSION......
  • 根composer.json需要php^8.0,但您的php版本(7.4.27)不满足该要求
    我安装了php7.4,但当我在项目中写入composerinstall时,我看到了以下错误:Rootcomposer.jsonrequiresphp^8.0butyourphpversion(7.4.27)doesnotsatisfythatreq......
  • Java签名排序,实现php的ksort升序排序
    php这边是需要使用ksort排序生成签名平台要求通用签名生成步骤按照键字母进行正序排序(ASCII码从小到大排序【字典序】)#排序之后的参数按照key+value+key+val......
  • php head topN算法
    原文https://diffnest.github.io/2019/07/01/PHP小顶堆实现TopK/<?phpclassTopk{public$top;public$topkArr=array();public$topkList=array();......
  • PHPMyWind编辑器支持pdf粘贴
    ​ 如何做到ueditor批量上传word图片?1、前端引用代码<!DOCTYPE html PUBLIC "-//W3C//DTDXHTML1.0Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml......
  • BM25 二叉树的后序遍历
    https://www.nowcoder.com/practice/1291064f4d5d4bdeaefbf0dd47d78541?tpId=295&tqId=2291301&ru=/exam/oj&qru=/ta/format-top101/question-ranking&sourceUrl=%2Fexam%2......