PHP数组在C层面是如何实现的? [英] How is the PHP array implemented on the C level?

查看:37
本文介绍了PHP数组在C层面是如何实现的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP array 是 PHP 的核心特性之一.它是稀疏的,允许在同一个数组中存在多种类型的键,并支持集合、字典、数组、堆栈/队列和迭代功能.

The PHP array is one of PHP's core features. It is sparse, allows multi-typed keys in the same array, and supports set, dictionary, array, stack/queue and iterative functionality.

但是在使用 PHP 一段时间之后,我发现很多 array_* 函数比您第一眼想象的要慢得多.就像在一个非常大的数组(10000+)上的 array_rand 的情况一样.array_rand 实际上很慢,以至于在您使用 php 数组作为索引数组的情况下,像 rand( 0, array_length( $array ) - 1 ) 这样的函数运行速度比 array_rand 快得多.

But after working with PHP for a while now, I've found that quite a few of the array_* functions are much slower than you'd think at first glance. Like in the case of array_rand on a very large array (10000+). array_rand is so slow in fact, that in cases where your using the php array as an indexed array, a function like rand( 0, array_length( $array ) - 1 ) runs MUCH faster than array_rand.

现在开始我的问题.

PHP 数组是如何在 C 级别实现的?这对于预测大量使用 PHP 数组数据类型的不同功能的函数的 Big O 非常有帮助.

How is the PHP array implemented on the C level? This would be very helpful for predicting the Big O of a function that heavily uses the different functionality of the PHP array datatype.

推荐答案

PHP 关联数组实际上是 的实现哈希表.

PHP associative arrays are in fact implementation of HashTables.

在内部,可以制作数值数组或关联数组.如果把它们组合起来,就是关联数组.

Internally, it is possible to make numeric arrays or associative arrays. If you combine them, it is associative array.

在数值数组中,它与 C 非常相似.您有指向 ZVAL 结构的指针数组.

In numeric arrays, it is very similar to C. You have array of pointers to ZVAL structs.

因为指针是固定长度的(我们称之为 n),所以偏移量 (x) 的计算很容易:x * n.

Because pointers have fixed-length (let's call it n), the offset (x) calculation is easy: x * n.

在 PHP 中类型是 ZVAL 结构(因为它以这种方式实现动态类型),但它也有助于关联数组,因为您可以假设固定长度.所以即使直接访问数组比较慢,仍然被认为是O(1).

In PHP types are ZVAL structs (because that way it implements dynamic types), but it also helps in associative array, because you can assume fixed-length. So even if direct access to array is slower, it is still considered O(1).

那么字符串键会发生什么?PHP 使用哈希函数将它们转换为整数.

So what happens in string keys? PHP uses hash function to convert them to intergers.

在数字和关联数组中搜索具有相似的效率,因为它们在内部都是数字.

Searching in numeric and associative array has similar efficiency, because internally they are all numeric.

由于额外的级别(散列函数),仅直接访问数组键的速度较慢.

Only direct-access to array keys is slower, because of the additional level (hash function).

这篇关于PHP数组在C层面是如何实现的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆