undefined
undefined

Reputation: 2499

The speed of variables vs arrays in php

I have abit of a silly question. I was just wondering. Whilst coding im sometimes tend to, if I have lot of variables that relate to a specific entity, create an associative array using key value pairs to define these entities.

What Id like to know is, Im aware that they all get saved in memory but which method is smaller/faster, creating a few variables or creating an array with keys and values of the variables

Below are some examples:

$apples  = 'apples'; 
$grapes  = 'some grapes';
$bananas = 'lots of bananas';

$fruits = ['apples' => 'apples', 'grapes' => 'some grapes', 'bananas' => 'lots of bananas'];

What I'll be using this for is looping over entries from the database and defining values to populate in my markup.

Upvotes: 3

Views: 1910

Answers (3)

mickmackusa
mickmackusa

Reputation: 48100

Speed and memory are likely to be irrelevant. Write clean, direct code.

If you are going to be iterating or searching these values, use an array.

As a fundamental rule, I don't declare single-use variables. Only in fringe cases where readability is dramatically improved do I break this rule.

Upvotes: 3

Nathan Barteaux
Nathan Barteaux

Reputation: 11

Using the array in PHP could possibly be slower than variables. However, it's not worth looking into. Focus on readability instead.

Upvotes: 1

phpforcoders
phpforcoders

Reputation: 326

Lets Try

Test 1

With 6 PHP variables

$makevar1 = 'checkspeed';
$makevar2 = 'checkspeed';
$makevar3 = 'checkspeed';
$makevar4 = 'checkspeed';
$makevar5 = 'checkspeed';
$makevar6 = 'checkspeed';

print_r(memory_get_usage()); 

Result is 458056

Test 2

With 6 array keys

$makevar = array();
$makevar['var1'] = 'checkspeed';
$makevar['var2'] = 'checkspeed';
$makevar['var3'] = 'checkspeed';
$makevar['var4'] = 'checkspeed';
$makevar['var5'] = 'checkspeed';
$makevar['var6'] = 'checkspeed';

print_r(memory_get_usage());

Result is 459168

Final Result: Accessing a variable is faster than array.

Upvotes: 2

Related Questions