A Study of PHP Arrays: Performance vs Memory

Written by AbiusX on . Posted in Development

While working on PureTextRender package, I realized some serious limits in PHP arrays. The mentioned package renders text into BMP images using pure PHP (no GD), and for that it requires a lot of arrays to be filled and traversed. The original package only supported small images due to typical PHP memory limit (128MB) though images were monochrome BMP! Before going any further, let’s see some PHP benchmark code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
//C Array Performance
#include <sys/time.h>
#include <stdio.h>
struct timeval timevar;
int main()
{
	int i=0;
 
	gettimeofday(&timevar, NULL); 
	long microsec = ((unsigned long long)timevar.tv_sec * 1000000) + timevar.tv_usec,microsec2;
 
	int a[1024*1024]; //1 microseconds
 
	gettimeofday(&timevar, NULL); 
	microsec2 = ((unsigned long long)timevar.tv_sec * 1000000) + timevar.tv_usec;
	printf("%lu microseconds\n",microsec2-microsec);
	microsec=microsec2;
 
	for (i=0;i<1024*1024;++i) //2016 microseconds
		;
 
	gettimeofday(&timevar, NULL); 
	microsec2 = ((unsigned long long)timevar.tv_sec * 1000000) + timevar.tv_usec;
	printf("%lu microseconds\n",microsec2-microsec);
	microsec=microsec2;
 
	for (i=0;i<1024*1024;++i) //3813 microseconds
		a[i]=i;
 
	gettimeofday(&timevar, NULL); 
	microsec2 = ((unsigned long long)timevar.tv_sec * 1000000) + timevar.tv_usec;
	printf("%lu microseconds\n",microsec2-microsec);
	microsec=microsec2;
	return 0;
}

 

Memory Optimized Arrays

It doesn’t appear like one could improve performance of PHP arrays beyond what SplFixedArray already does, but there might be cases where a piece of code requires denser memory access to perform its task. The PureTextRender package mentioned above is one of those instances, where it needs a huge bitmap array, every element of which could be only a bit, fills it with generated content, passes it through distort, scale and rotate functions; each of which runs only one linear pass over the data, and dumps the output either into a file or onto the screen. Since passing through 128MB of data took half a second, and a typical image generating code would run up to 5 seconds, we could tolerate a denser structure that is up to 10 times slower than native PHP arrays.

Unfortunately, the only underlying data structure of PHP is native arrays, even SplFixedArray is not available unless one has PHP 5.3+. To do any sort of optimized (but not compressed) data storage, we would require a flat (preferably continues) storage system to use in PHP, similar to good ol’ C arrays.

Welcome

I'm Abbas Naderi Afooshteh, also known as Abius and AbiusX. A software engineer and a renowned security expert, I'm currently OWASP chapter leader of Iran, owner of many OWASP projects, a member of ISSECO and CIO of Etebaran Informatics. For more details of what I do and what I can do, check my resume.