has been tangled in PHP statistical array length function count (), as well as how strlen, its efficiency is O (1) or O (n) it? Recently read PHP source code, summed up the next. The analysis is as follows:
All the variables Zend to PHP are stored in the same way as the shared body, while the preservation of the string and the save of the array are different, and the arrays are stored in the form of a hash table. The variables shared by PHP are described below
/ * * zval
The structure of the hash table is this:
typedef struct _HASHTABLE {UINT ntablesize; uint ntablemask; uint nnumofelements; ulong nnextfreeelement;
The general variable ( string ) when using strlen to obtain the length, actually obtains is ZVALUE_VALUE.STR this structure the Len attribute, the efficiency O (1) times, In particular, strlen does not have a core implementation in PHP, but instead uses the macro definition in Zend to obtain:
And for the Count operation of an array, there are actually two results, and the second parameter, mode, is mentioned in the Count's API, which indicates whether a re-statistic is required, and its re-statistics will iterate through the array, efficiently O (N) [N: Length], by default is not re-statistics, then this time will be directly output hashtable in the nnumofelements, at this time the efficiency is also O (1) times: The Count code is as follows:
Php_function (count) {zval *array; long mode = Count_normal; if (Zend_parse_parameters (Zend_num_args () tsrmls_cc, "Z|l", & Amp;array, &mode) = = FAILURE) {return;} switch (Z_type_p (array)) {case Is_null:return_long (0); Y:return_long (php_count_recursive (array, mode TSRMLS_CC)); Break //php_count_recursive implementation of static int php_count_recursive (Zval *array, long mode TSRMLS_DC)/* {{{* * * {long cnt = 0; Zval **element; if (z_type_p (array) = = Is_array) {//Error handling if (z_arrval_p (array)->napplycount > 1) {php_error_docref (NULL tsrmls_cc, E_warning, "recursion detected"); return 0; The length cnt = zend_hash_num_elements (z_arrval_p (array)) is obtained directly via zend_hash_num_elements; If you specify a need to re-count, you will enter a cyclic statistic if (mode = = count_recursive) {hashposition pos; for (ZEND_HASH_INTERNAL_POINTER_RESET_EX (z_ Arrval_p (array), &pos); ZEND_HASH_GET_CURRENT_DATA_EX (z_arrval_p (array), (void * *) &element, &pos) = = SUCCESS; ZEND_HASH_MOVE_FORWARD_EX (z_arrval_p (array), &pos)) { Z_arrval_p (Array)->napplycount++; CNT + = Php_count_recursive (*element, count_recursive tsrmls_cc); Z_arrval_p (Array)->napplycount--; }}} return cnt; }//zend/zend_hash.c//zend_hash_num_elements Implementation ZEND_API int zend_hash_num_elements (const HashTable *ht) {IS_ Consistent (HT); Return ht->nnumofelements; }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.