0

I've been wooking with some strings in php to make my own framework... There's something that "bothers" me.

$var = "hello!";

$arr = array("h","e","l","l","o","!");

Can someone tell me which one ($var or $arr) uses more memory then the other one? And why?

At first sight I would say the array would use more memory since it has to position each character inside the array itself, but I'm not sure.

1
  • 1
    One string is one zval value, an array of strings is multiple zvals plus an array zval. Each zval adds a bit of overhead. In practice this information is mostly irrelevant, since you should be writing one or the other depending on your intended use, not based on minimal differences in memory consumption. Commented Nov 5, 2014 at 8:19

2 Answers 2

3

The array will use more memory than the string

A string and an array are zval structures in their own right, but each element in the array is a string as well, each with its own zval; arrays take a surprising amount of memory. There is also the fact that an array element comprises both a key and a value, each using memory

Take a read of this article to see just how much memory is used by an array structure

Sign up to request clarification or add additional context in comments.

Comments

2

The array takes (a lot!) more memory.

A string in PHP is an object in memory that holds (for example) the length and a pointer to the actual data in memory. I think that on most platforms that gives you 32 bits for the length and 64 bits for the pointer. With 16-byte alignment requirements from some CPUs, this means that each string will be at least 32 bytes (descriptor + actual data) - even if it's only a single character.

The array from your example contains 6 strings. That will be 192 bytes plus the overhead of storing an array, which is not insignificant either (count on at least 128 more bytes).

Disclaimer: the numbers used in this answer are a rough approximation - expect far more overhead than mentioned here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.