1

I saw this post, but didn't quite understand it and it didn't quite answer my question. Also - it seems to suggest that arrays are slower. I thought: that cannot be!

When all else is equal, and when aiming for speed, what is the best way to assign variables in an array?

Is this better:

$part1 = "a";
$part2 = "b";
$part3 = "c";
$part4 = "d";

(Sure, I know this doesn't allow you to interact with the data like you would with an array, but let's say you didn't need to.)

Is this better:

$part[1] = "a";
$part[2] = "b";
$part[3] = "c";
$part[4] = "d";

Is this better:

$part = array("a","b","c","d");

Or something else? And what are the mechanics behind why one is better than the others?

Also - does it depend on the number of elements being assigned? How does the answer change when talking about multidimensional arrays, different data types, or different languages? Also, does it change if I initialize the array then add elements to it?

Community
  • 1
  • 1
SimaPro
  • 1,164
  • 4
  • 14
  • 28

1 Answers1

0

An array is an array, no matter how you specify or assign variables to it. Once you create an array, it is put into memeory (unless you're utilizing SplFixedArray) and arrays in memory grow very quickly.

Consider this article which does a deeper look into how resource intensive arrays are: http://nikic.github.io/2011/12/12/How-big-are-PHP-arrays-really-Hint-BIG.html

From the article:

In this post I want to investigate the memory usage of PHP arrays (and values in general) using the following script as an example, which creates 100000 unique integer array elements and measures the resulting memory usage:

<?php
$startMemory = memory_get_usage();
$array = range(1, 100000);
echo memory_get_usage() - $startMemory, ' bytes';

How much would you expect it to be? Simple, one integer is 8 bytes (on a 64 bit unix machine and using the long type) and you got 100000 integers, so you obviously will need 800000 bytes. That’s something like 0.76 MBs.

Now try and run the above code. You can do it online if you want. This gives me 14649024 bytes. Yes, you heard right, that’s 13.97 MB - eightteen times more than we estimated.

Michael Irigoyen
  • 22,513
  • 17
  • 89
  • 131
  • Yikes!! So does that mean if I have the ability - I should just use single variables?? As in The first example above? – SimaPro Aug 26 '13 at 02:29
  • Also, a tl;dr for the article above, or what I got from it anyway: PHP is dynamic and flexible thus compromising on speed and efficiency. It has to run a lot of separate processes to handle arrays, hence the large memory requirement. Thanks for the link! – SimaPro Aug 26 '13 at 02:31