PHP中array_keys和array_unique函數(shù)源碼的分析
性能分析
從運(yùn)行性能上分析,看看下面的測(cè)試代碼:
$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";
運(yùn)行結(jié)果如下:
從上圖可以看到,使用array_unique函數(shù)需要0.069s;使用array_flip后再使用array_keys函數(shù)需要0.00152s;使用兩次array_flip函數(shù)需要0.00146s。
測(cè)試結(jié)果表明,使用array_flip后再調(diào)用array_keys函數(shù)比array_unique函數(shù)快。那么,具體原因是什么呢?讓我們看看在PHP底層,這兩個(gè)函數(shù)是怎么實(shí)現(xiàn)的。
源碼分析
/* {{{ 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; //程序解析參數(shù) if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|zb", &input, &search_value, &strict) == FAILURE) { return; } // 如果strict是true,則設(shè)置is_equal_func為is_identical_function,即全等比較 if (strict) { is_equal_func = is_identical_function; } /* 根據(jù)search_vale初始化返回的數(shù)組大小 */ 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; /* 遍歷輸入的數(shù)組參數(shù),然后添加鍵值到返回的數(shù)組 */ zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(input), &pos);//重置指針 //循環(huán)遍歷數(shù)組 while (zend_hash_get_current_data_ex(Z_ARRVAL_P(input), (void **)&entry, &pos) == SUCCESS) { // 如果search_value不為空 if (search_value != NULL) { // 判斷search_value與當(dāng)前的值是否相同,并將比較結(jié)果保存到add_key變量 is_equal_func(&res, search_value, *entry TSRMLS_CC); add_key = zval_is_true(&res); } if (add_key) { // 創(chuàng)建一個(gè)zval結(jié)構(gòu)體 MAKE_STD_ZVAL(new_val); // 根據(jù)鍵值是字符串還是整型數(shù)字將值插入到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); // 此函數(shù)負(fù)責(zé)將值插入到return_value中,如果鍵值已存在,則使用新值更新對(duì)應(yīng)的值,否則直接插入 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; } } // 移動(dòng)到下一個(gè) zend_hash_move_forward_ex(Z_ARRVAL_P(input), &pos); } } /* }}} */
以上是array_keys函數(shù)底層的源碼。為方便理解,筆者添加了一些中文注釋。如果需要查看原始代碼,可以點(diǎn)擊查看。這個(gè)函數(shù)的功能就是新建一個(gè)臨時(shí)數(shù)組,然后將鍵值對(duì)重新復(fù)制到新的數(shù)組,如果復(fù)制過(guò)程中有重復(fù)的鍵值出現(xiàn),那么就用新的值替換。這個(gè)函數(shù)的主要步驟是地57和63行調(diào)用的zend_hash_next_index_insert函數(shù)。該函數(shù)將元素插入到數(shù)組中,如果出現(xiàn)重復(fù)的值,則使用新的值更新原鍵值指向的值,否則直接插入,時(shí)間復(fù)雜度是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; // 解析數(shù)組參數(shù) if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &array) == FAILURE) { return; } // 初始化返回?cái)?shù)組 array_init_size(return_value, zend_hash_num_elements(Z_ARRVAL_P(array))); // 重置指針 zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(array), &pos); // 遍歷每個(gè)元素,并執(zhí)行鍵<->值交換操作 while (zend_hash_get_current_data_ex(Z_ARRVAL_P(array), (void **)&entry, &pos) == SUCCESS) { // 初始化一個(gè)結(jié)構(gòu)體 MAKE_STD_ZVAL(data); // 將原數(shù)組的值賦值為新數(shù)組的鍵 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; } // 將原數(shù)組的鍵賦值為新數(shù)組的值,如果有重復(fù)的,則使用新值覆蓋舊值 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!"); } // 下一個(gè) zend_hash_move_forward_ex(Z_ARRVAL_P(array), &pos); } } /* }}} */
上面就是是array_flip函數(shù)的源碼。點(diǎn)擊鏈接查看原始代碼。這個(gè)函數(shù)主要的做的事情就是創(chuàng)建一個(gè)新的數(shù)組,遍歷原數(shù)組。在26行開始將原數(shù)組的值賦值為新數(shù)組的鍵,然后在37行開始將原數(shù)組的鍵賦值為新數(shù)組的值,如果有重復(fù)的,則使用新值覆蓋舊值。整個(gè)函數(shù)的時(shí)間復(fù)雜度也是O(n)。因此,使用了array_flip之后再使用array_keys的時(shí)間復(fù)雜度是O(n)。
接下來(lái),我們看看array_unique函數(shù)的源碼。點(diǎn)擊鏈接查看原始代碼。
/* {{{ 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; // 解析參數(shù) if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|l", &array, &sort_type) == FAILURE) { return; } // 設(shè)置比較函數(shù) php_set_compare_func(sort_type TSRMLS_CC); // 初始化返回?cái)?shù)組 array_init_size(return_value, zend_hash_num_elements(Z_ARRVAL_P(array))); // 將值拷貝到新數(shù)組 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; } /* 根據(jù)target_hash buckets的指針創(chuàng)建數(shù)組并排序 */ 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); /* 遍歷排序好的數(shù)組,然后刪除重復(fù)的元素 */ 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); } /* }}} */
可以看到,這個(gè)函數(shù)初始化一個(gè)新的數(shù)組,然后將值拷貝到新數(shù)組,然后在45行調(diào)用排序函數(shù)對(duì)數(shù)組進(jìn)行排序,排序的算法是zend引擎的塊樹排序算法。接著遍歷排序好的數(shù)組,刪除重復(fù)的元素。整個(gè)函數(shù)開銷最大的地方就在調(diào)用排序函數(shù)上,而快排的時(shí)間復(fù)雜度是O(nlogn),因此,該函數(shù)的時(shí)間復(fù)雜度是O(nlogn)。
結(jié)論
因?yàn)閍rray_unique底層調(diào)用了快排算法,加大了函數(shù)運(yùn)行的時(shí)間開銷,導(dǎo)致整個(gè)函數(shù)的運(yùn)行較慢。這就是為什么array_keys比array_unique函數(shù)更快的原因。
相關(guān)文章
PHP實(shí)現(xiàn)的迪科斯徹(Dijkstra)最短路徑算法實(shí)例
這篇文章主要介紹了PHP實(shí)現(xiàn)的迪科斯徹(Dijkstra)最短路徑算法,簡(jiǎn)單描述了迪科斯徹(Dijkstra)最短路徑算法的概念、功能并結(jié)合具體實(shí)例形式分析了php實(shí)現(xiàn)迪科斯徹(Dijkstra)最短路徑算法的相關(guān)步驟與操作技巧,需要的朋友可以參考下2017-09-09php實(shí)現(xiàn)每天自動(dòng)變換隨機(jī)問(wèn)候語(yǔ)的方法
這篇文章主要介紹了php實(shí)現(xiàn)每天自動(dòng)變換隨機(jī)問(wèn)候語(yǔ)的方法,涉及時(shí)間與數(shù)組的相關(guān)操作技巧,需要的朋友可以參考下2015-05-05php實(shí)現(xiàn)數(shù)字轉(zhuǎn)億萬(wàn)單位的示例代碼
這篇文章主要為大家詳細(xì)介紹了php如何實(shí)現(xiàn)數(shù)字轉(zhuǎn)億萬(wàn)單位,文中的示例代碼講解詳細(xì),具有一定的借鑒價(jià)值,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-11-11PHP數(shù)字前補(bǔ)0的自帶函數(shù)sprintf 和number_format的用法(詳解)
下面小編就為大家?guī)?lái)一篇PHP數(shù)字前補(bǔ)0的自帶函數(shù)sprintf 和number_format的用法(詳解)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-02-02thinkphp備份數(shù)據(jù)庫(kù)的方法分享
這篇文章主要介紹了thinkphp備份數(shù)據(jù)庫(kù)的方法分享,非常的簡(jiǎn)單實(shí)用,推薦給有需要的小伙伴們2015-01-01php number_format() 函數(shù)通過(guò)千位分組來(lái)格式化數(shù)字的實(shí)現(xiàn)代碼
以下是對(duì)php中的number format()函數(shù)通過(guò)千位分組來(lái)格式化數(shù)字的實(shí)現(xiàn)代碼進(jìn)行了詳細(xì)的分析介紹,需要的朋友可以過(guò)來(lái)參考下2013-08-08