Why is array_key_exists 1000x slower than isset on referenced arrays?

后端 未结 3 2084
轻奢々
轻奢々 2020-12-31 00:56

I have found that array_key_exists is over 1000x slower than isset at check if a key is set in an array reference. Does anyone that has an understa

3条回答
  •  既然无缘
    2020-12-31 01:55

    Here is the source of the array_key_exists function for 5.2.17. You can see that even if the key is null, PHP attempts to compute a hash. Although it's interesting that if you remove

    // $my_array_ref[$i] = NULL;
    

    then it performs better. There must be multiple hash lookups occuring.

    /* {{{ proto bool array_key_exists(mixed key, array search)
       Checks if the given key or index exists in the array */
    PHP_FUNCTION(array_key_exists)
    {
        zval **key,                 /* key to check for */
             **array;               /* array to check in */
    
        if (ZEND_NUM_ARGS() != 2 ||
            zend_get_parameters_ex(ZEND_NUM_ARGS(), &key, &array) == FAILURE) {
            WRONG_PARAM_COUNT;
        }
    
        if (Z_TYPE_PP(array) != IS_ARRAY && Z_TYPE_PP(array) != IS_OBJECT) {
            php_error_docref(NULL TSRMLS_CC, E_WARNING, "The second argument should be either an array or an object");
            RETURN_FALSE;
        }
    
        switch (Z_TYPE_PP(key)) {
            case IS_STRING:
                if (zend_symtable_exists(HASH_OF(*array), Z_STRVAL_PP(key), Z_STRLEN_PP(key)+1)) {
                    RETURN_TRUE;
                }
                RETURN_FALSE;
            case IS_LONG:
                if (zend_hash_index_exists(HASH_OF(*array), Z_LVAL_PP(key))) {
                    RETURN_TRUE;
                }
                RETURN_FALSE;
            case IS_NULL:
                if (zend_hash_exists(HASH_OF(*array), "", 1)) {
                    RETURN_TRUE;
                }
                RETURN_FALSE;
    
            default:
                php_error_docref(NULL TSRMLS_CC, E_WARNING, "The first argument should be either a string or an integer");
                RETURN_FALSE;
        }
    
    }
    

提交回复
热议问题