Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a simple, fast array in PHP?

Tags:

arrays

php

I need a simple array that uses minimum memory in PHP. I want the exact C++ equivalent of an allocated block of memory where you can iterate using indices only. I found out that arrays in PHP use more memory than let's say : size*type_size (I guess for storing key values, etc). Is there anything more unsophisticated and simple ?

EDIT:

Thank you all.

Yes, I thought the idea of the string immediately after posting the question. I needed a boolean array, so that seemed to work. It's just a little slower to get/set it's characters.

Judy arrays also seem interesting but I haven't tried it yet.

I've tried SplFixedArray but it seemed that it used the same amount of memory to normal arrays (except if I've missed sth on the way).

like image 720
NoOne Avatar asked Nov 26 '11 11:11

NoOne


2 Answers

You could use the SplFixedArray which seems to meet your demands.

like image 157
str Avatar answered Oct 02 '22 06:10

str


I need a simple array that uses minimum memory in PHP.

The speediest array type in PHP is actually the string. It also is the least memory-hungry; the closest you get to a C equivalent data structure.

 $byte = ord($string[123]);

It's indexed. But the limitation is of course that it only works on byte values. (You didn't exactly elaborate on your needs. So here is your generic answer.)

As alternative to the fixed length SplFixedArray PHP also has an extension for Judy arrays. They are associative, but conserve memory in comparison to PHPs; and are supposedly a bit speedier. (Doesn't make much sense in a scripting language to care about that, but hey.)

like image 33
mario Avatar answered Oct 02 '22 05:10

mario