侯体宗的博客
  • 首页
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

PHP中array_keys和array_unique函数源码的分析

php  /  管理员 发布于 7年前   156

性能分析

从运行性能上分析,看看下面的测试代码:

$test=array();for($run=0; $run<10000; $run++)$test[]=rand(0,100);$time=microtime(true);$out = array_unique($test);$time=microtime(true)-$time;echo 'Array Unique: '.$time."\n";$time=microtime(true);$out=array_keys(array_flip($test));$time=microtime(true)-$time;echo 'Keys Flip: '.$time."\n";$time=microtime(true);$out=array_flip(array_flip($test));$time=microtime(true)-$time;echo 'Flip Flip: '.$time."\n";

运行结果如下:

从上图可以看到,使用array_unique函数需要0.069s;使用array_flip后再使用array_keys函数需要0.00152s;使用两次array_flip函数需要0.00146s。

测试结果表明,使用array_flip后再调用array_keys函数比array_unique函数快。那么,具体原因是什么呢?让我们看看在PHP底层,这两个函数是怎么实现的。

源码分析

/* {{{ proto array array_keys(array input [, mixed search_value[, bool strict]])  Return just the keys from the input array, optionally only for the specified       search_value */PHP_FUNCTION(array_keys){  //变量定义  zval *input,        /* Input array */     *search_value = NULL,  /* Value to search for */     **entry,        /* An entry in the input array */      res,          /* Result of comparison */     *new_val;        /* New value */  int  add_key;        /* Flag to indicate whether a key should be added */  char *string_key;      /* String key */  uint  string_key_len;  ulong num_key;        /* Numeric key */  zend_bool strict = 0;    /* do strict comparison */  HashPosition pos;  int (*is_equal_func)(zval *, zval *, zval * TSRMLS_DC) = is_equal_function;  //程序解析参数  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|zb", &input, &search_value, &strict) == FAILURE) {    return;  }  // 如果strict是true,则设置is_equal_func为is_identical_function,即全等比较  if (strict) {    is_equal_func = is_identical_function;  }  /* 根据search_vale初始化返回的数组大小 */  if (search_value != NULL) {    array_init(return_value);  } else {    array_init_size(return_value, zend_hash_num_elements(Z_ARRVAL_P(input)));  }  add_key = 1;  /* 遍历输入的数组参数,然后添加键值到返回的数组 */  zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(input), &pos);//重置指针  //循环遍历数组  while (zend_hash_get_current_data_ex(Z_ARRVAL_P(input), (void **)&entry, &pos) == SUCCESS) {    // 如果search_value不为空    if (search_value != NULL) {      // 判断search_value与当前的值是否相同,并将比较结果保存到add_key变量      is_equal_func(&res, search_value, *entry TSRMLS_CC);      add_key = zval_is_true(&res);    }    if (add_key) {      // 创建一个zval结构体      MAKE_STD_ZVAL(new_val);      // 根据键值是字符串还是整型数字将值插入到return_value中      switch (zend_hash_get_current_key_ex(Z_ARRVAL_P(input), &string_key, &string_key_len, &num_key, 1, &pos)) {        case HASH_KEY_IS_STRING:          ZVAL_STRINGL(new_val, string_key, string_key_len - 1, 0);          // 此函数负责将值插入到return_value中,如果键值已存在,则使用新值更新对应的值,否则直接插入          zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &new_val, sizeof(zval *), NULL);          break;        case HASH_KEY_IS_LONG:          Z_TYPE_P(new_val) = IS_LONG;          Z_LVAL_P(new_val) = num_key;          zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &new_val, sizeof(zval *), NULL);          break;      }    }    // 移动到下一个    zend_hash_move_forward_ex(Z_ARRVAL_P(input), &pos);  }}/* }}} */

以上是array_keys函数底层的源码。为方便理解,笔者添加了一些中文注释。如果需要查看原始代码,可以点击查看。这个函数的功能就是新建一个临时数组,然后将键值对重新复制到新的数组,如果复制过程中有重复的键值出现,那么就用新的值替换。这个函数的主要步骤是地57和63行调用的zend_hash_next_index_insert函数。该函数将元素插入到数组中,如果出现重复的值,则使用新的值更新原键值指向的值,否则直接插入,时间复杂度是O(n)。

/* {{{ proto array array_flip(array input)  Return array with key <-> value flipped */PHP_FUNCTION(array_flip){  // 定义变量  zval *array, **entry, *data;  char *string_key;  uint str_key_len;  ulong num_key;  HashPosition pos;  // 解析数组参数  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &array) == FAILURE) {    return;  }  // 初始化返回数组  array_init_size(return_value, zend_hash_num_elements(Z_ARRVAL_P(array)));  // 重置指针  zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(array), &pos);  // 遍历每个元素,并执行键<->值交换操作  while (zend_hash_get_current_data_ex(Z_ARRVAL_P(array), (void **)&entry, &pos) == SUCCESS) {    // 初始化一个结构体    MAKE_STD_ZVAL(data);    // 将原数组的值赋值为新数组的键    switch (zend_hash_get_current_key_ex(Z_ARRVAL_P(array), &string_key, &str_key_len, &num_key, 1, &pos)) {      case HASH_KEY_IS_STRING:        ZVAL_STRINGL(data, string_key, str_key_len - 1, 0);        break;      case HASH_KEY_IS_LONG:        Z_TYPE_P(data) = IS_LONG;        Z_LVAL_P(data) = num_key;        break;    }    // 将原数组的键赋值为新数组的值,如果有重复的,则使用新值覆盖旧值    if (Z_TYPE_PP(entry) == IS_LONG) {      zend_hash_index_update(Z_ARRVAL_P(return_value), Z_LVAL_PP(entry), &data, sizeof(data), NULL);    } else if (Z_TYPE_PP(entry) == IS_STRING) {      zend_symtable_update(Z_ARRVAL_P(return_value), Z_STRVAL_PP(entry), Z_STRLEN_PP(entry) + 1, &data, sizeof(data), NULL);    } else {      zval_ptr_dtor(&data); /* will free also zval structure */      php_error_docref(NULL TSRMLS_CC, E_WARNING, "Can only flip STRING and INTEGER values!");    }    // 下一个    zend_hash_move_forward_ex(Z_ARRVAL_P(array), &pos);  }}/* }}} */

上面就是是array_flip函数的源码。点击链接查看原始代码。这个函数主要的做的事情就是创建一个新的数组,遍历原数组。在26行开始将原数组的值赋值为新数组的键,然后在37行开始将原数组的键赋值为新数组的值,如果有重复的,则使用新值覆盖旧值。整个函数的时间复杂度也是O(n)。因此,使用了array_flip之后再使用array_keys的时间复杂度是O(n)。

接下来,我们看看array_unique函数的源码。点击链接查看原始代码。

/* {{{ proto array array_unique(array input [, int sort_flags])  Removes duplicate values from array */PHP_FUNCTION(array_unique){  // 定义变量  zval *array, *tmp;  Bucket *p;  struct bucketindex {    Bucket *b;    unsigned int i;  };  struct bucketindex *arTmp, *cmpdata, *lastkept;  unsigned int i;  long sort_type = PHP_SORT_STRING;  // 解析参数  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|l", &array, &sort_type) == FAILURE) {    return;  }  // 设置比较函数  php_set_compare_func(sort_type TSRMLS_CC);  // 初始化返回数组  array_init_size(return_value, zend_hash_num_elements(Z_ARRVAL_P(array)));  // 将值拷贝到新数组  zend_hash_copy(Z_ARRVAL_P(return_value), Z_ARRVAL_P(array), (copy_ctor_func_t) zval_add_ref, (void *)&tmp, sizeof(zval*));  if (Z_ARRVAL_P(array)->nNumOfElements <= 1) {  /* 什么都不做 */    return;  }  /* 根据target_hash buckets的指针创建数组并排序 */  arTmp = (struct bucketindex *) pemalloc((Z_ARRVAL_P(array)->nNumOfElements + 1) * sizeof(struct bucketindex), Z_ARRVAL_P(array)->persistent);  if (!arTmp) {    zval_dtor(return_value);    RETURN_FALSE;  }  for (i = 0, p = Z_ARRVAL_P(array)->pListHead; p; i++, p = p->pListNext) {    arTmp[i].b = p;    arTmp[i].i = i;  }  arTmp[i].b = NULL;  // 排序  zend_qsort((void *) arTmp, i, sizeof(struct bucketindex), php_array_data_compare TSRMLS_CC);  /* 遍历排序好的数组,然后删除重复的元素 */  lastkept = arTmp;  for (cmpdata = arTmp + 1; cmpdata->b; cmpdata++) {    if (php_array_data_compare(lastkept, cmpdata TSRMLS_CC)) {      lastkept = cmpdata;    } else {      if (lastkept->i > cmpdata->i) {        p = lastkept->b;        lastkept = cmpdata;      } else {        p = cmpdata->b;      }      if (p->nKeyLength == 0) {        zend_hash_index_del(Z_ARRVAL_P(return_value), p->h);      } else {        if (Z_ARRVAL_P(return_value) == &EG(symbol_table)) {          zend_delete_global_variable(p->arKey, p->nKeyLength - 1 TSRMLS_CC);        } else {          zend_hash_quick_del(Z_ARRVAL_P(return_value), p->arKey, p->nKeyLength, p->h);        }      }    }  }  pefree(arTmp, Z_ARRVAL_P(array)->persistent);}/* }}} */

可以看到,这个函数初始化一个新的数组,然后将值拷贝到新数组,然后在45行调用排序函数对数组进行排序,排序的算法是zend引擎的块树排序算法。接着遍历排序好的数组,删除重复的元素。整个函数开销最大的地方就在调用排序函数上,而快排的时间复杂度是O(nlogn),因此,该函数的时间复杂度是O(nlogn)。

结论

因为array_unique底层调用了快排算法,加大了函数运行的时间开销,导致整个函数的运行较慢。这就是为什么array_keys比array_unique函数更快的原因。

您可能感兴趣的文章:

  • PHP获取数组中某元素的位置及array_keys函数应用
  • php数组函数序列之array_keys() - 获取数组键名
  • php 多文件上传的实现实例
  • php 修改上传文件大小限制实例详解
  • php 页面之间传值的三种方法实例代码
  • 详解php中空字符串和0之间的关系
  • php array_keys 返回数组的键名


  • 上一条:
    关于PHP 如何用 curl 读取 HTTP chunked 数据
    下一条:
    PHP+JS三级菜单联动菜单实现方法
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • 用Time Warden监控PHP中的代码处理时间(0个评论)
    • 在PHP中使用array_pop + yield实现读取超大型目录功能示例(0个评论)
    • Property Hooks RFC在PHP 8.4中越来越接近现实(0个评论)
    • 近期文章
    • 在windows10中升级go版本至1.24后LiteIDE的Ctrl+左击无法跳转问题解决方案(0个评论)
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(95个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2017-06
    • 2017-07
    • 2017-08
    • 2017-09
    • 2017-11
    • 2017-12
    • 2018-01
    • 2018-02
    • 2018-03
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-09
    • 2021-02
    • 2021-03
    • 2021-04
    • 2021-05
    • 2021-06
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-10
    • 2021-11
    • 2021-12
    • 2022-01
    • 2022-02
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-08
    • 2023-09
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-02
    • 2024-03
    • 2024-04
    • 2024-05
    • 2024-06
    • 2024-07
    • 2024-09
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客