search
HomeBackend DevelopmentPHP Tutorial php的数组跟spl固定数组

php的数组和spl固定数组
php固定数组隶属于php标准库(spl)的一种数据结构。和php普通数组相比,固定数组只能用整形定义其下标,并且如名字所示,是固定长度,它的优点是比普通数组占用的内存少,而且更快速,具体原因下文会做分析,先做一个简单的测试,将10W个a放入到数组中。

define("MAX", 100000);

//simple array
function simple_arr()
{
        $i = MAX;
	$arr = array();
	while ($i--)
		$arr[$i]= 'a';
}

// fix array
function fix_arr()
{	
	$i = MAX;
	$arr = new SplFixedArray(MAX);
	while ($i--)
		$arr[$i]= 'a';		
}

//fix array with set
function fix_set_arr()
{
	$i = MAX;
	$arr = new SplFixedArray(MAX);
	while ($i--)
		$arr->offsetSet($i, "a");
}

时间消耗

一般数组:0.084696054458618

固定数组:0.048405885696411

固定数组调用offsetSet方法复制:0.27650499343872

内存消耗

一般数组:9324672

固定数组:4800464

固定数组调用offsetSet方法复制:4800344


空间消耗对比

从空间和时间的效率来看,固定数组的消耗都比一般数组少了很可观。固定数组通过扩展中的内置函数offsetSet赋值比通过下标赋值时间慢的多,这个因为用扩展中的内置方法斤数组赋值,php内部需要多一次函数表的查询。

在空间方面,对一般数组,php内部是通过hashtable来存储,hashtable中的每一个槽位对应数组中的一个值,在php源码Zend/zend_hash.h中定义了hash相关的结构体定义和函数。

typedef struct bucket {
	ulong h;						/* Used for numeric indexing */
	uint nKeyLength;
	void *pData;
	void *pDataPtr;
	struct bucket *pListNext;
	struct bucket *pListLast;
	struct bucket *pNext;
	struct bucket *pLast;
	const char *arKey;
} Bucket;

typedef struct _hashtable {
	uint nTableSize;
	uint nTableMask;
	uint nNumOfElements;
	ulong nNextFreeElement;
	Bucket *pInternalPointer;	/* Used for element traversal */
	Bucket *pListHead;
	Bucket *pListTail;
	Bucket **arBuckets;
	dtor_func_t pDestructor;
	zend_bool persistent;
	unsigned char nApplyCount;
	zend_bool bApplyProtection;
#if ZEND_DEBUG
	int inconsistent;
#endif
} HashTable
	

如上面代码所示,一个10个元素的php数组所站的空间是sizeof(HashTable) + 10 * size(Bucket) + 元素本身占用空间,这是代码层面的算术,其实在php内部会复杂一点,HashTable的nTableSize永远是2^n,所以即使是10个元素,php内部通过 简单算法能实现占用2^4,也即16个槽位,所以实际占用空间是sizeof(HashTable) + 16 * sizeof(Bucket)  + 元素本身占用空间。(空间的计算只考虑下标是整数的情况下)

而对应固定数组直接通过用户传人的size大小初始化数组,如下面代码所示:同样10个元素的数组,所需要的空间只有10* 元素本身占用空间。

static void spl_fixedarray_init(spl_fixedarray *array, long size TSRMLS_DC) /* {{{ */
{
	if (size > 0) {
		array->size = 0; /* reset size in case ecalloc() fails */
		array->elements = ecalloc(size, sizeof(zval *));
		array->size = size;
	} else {
		array->elements = NULL;
		array->size = 0;
	}
}

时间方面对比

对于固定数组来说,对内存的申请一步到位了,当内存不够时候会报错,当内存用不完时,也就浪费在那里。

对于普通数组,因为是动态分配数组空间,由于预先不知道要有多少元素,php初始化空数组的的时候,默认8个槽位,但槽位不够的时候,会再分配*2的空间,当元素元素的数量大于hashTbale中的nTableSize的时候,会resize和rehash hashTable,在resize和rehash的过程中,时间的消耗相当可观了。

static int zend_hash_do_resize(HashTable *ht)
{
	Bucket **t;
#ifdef ZEND_SIGNALS
	TSRMLS_FETCH();
#endif

	IS_CONSISTENT(ht);

	if ((ht->nTableSize  0) {	/* Let's double the table size */
		t = (Bucket **) perealloc_recoverable(ht->arBuckets, (ht->nTableSize persistent);
		if (t) {
			HANDLE_BLOCK_INTERRUPTIONS();
			ht->arBuckets = t;
			ht->nTableSize = (ht->nTableSize nTableMask = ht->nTableSize - 1;
			zend_hash_rehash(ht);
			HANDLE_UNBLOCK_INTERRUPTIONS();
			return SUCCESS;
		}
		return FAILURE;
	}
	return SUCCESS;
}

ZEND_API int zend_hash_rehash(HashTable *ht)
{
	Bucket *p;
	uint nIndex;

	IS_CONSISTENT(ht);
	if (UNEXPECTED(ht->nNumOfElements == 0)) {
		return SUCCESS;
	}

	memset(ht->arBuckets, 0, ht->nTableSize * sizeof(Bucket *));
	p = ht->pListHead;
	while (p != NULL) {
		nIndex = p->h & ht->nTableMask;
		CONNECT_TO_BUCKET_DLLIST(p, ht->arBuckets[nIndex]);
		ht->arBuckets[nIndex] = p;
		p = p->pListNext;
	}
	return SUCCESS;
}


通过对比发现php普通数组的内存和时间消耗和固定数组相比大部分都用在了符号表上。php内部实现的一个重要思想是通过空间来换取时间,用hashTable能够快速定位到数据的元素,它甚至把hashTable设计成双向链表,又因为php数组空间是动态分配的,而内部是用c实现的,c语言对数组空间分配只有固定分配,为了实现让用户感觉php数组是动态分配空间的,只能通过resize和rehash实现,所以和固定数组比,相同数量的元素赋值,时间就变慢了。总之,普通数组和固定数组各有优劣,不能说固定数组时间和空间消耗低就是后,具体的情况需要考虑到具体的业务场景。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)