PHP的阵列是如何实现在C级? [英] How is the PHP array implemented on the C level?

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

问题描述

在PHP 阵列是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_rand 的一个非常大的阵列(10000+)上的情况。 array_rand 其实这么慢,那在你使用PHP数组索引数组的情况下,如兰特(0,array_length一个函数($数组) - 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.

现在到我的问题。

如何在C级别实现的PHP数组?这将是predicting,在很大程度上使用PHP数组类型的不同功能的功能的大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使用哈希函数将它们转换为intergers。

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天全站免登陆