LostPhysx
LostPhysx

Reputation: 3641

What is more performant, multiple Arrays or one Array containing multiple arrays?

What will be more performant and ressource friendlier?

To use

$array1=Array();
$array2=Array();
$array3=Array();

or:

$arr=Array();
$arr[] = Array();
$arr[] = Array();
$arr[] = Array();

And what is better to handle in the code when maintenance is required?

I have to handle about 2800 different arrays so the performance is very important.

Upvotes: 1

Views: 118

Answers (3)

Basic
Basic

Reputation: 26766

Maintainability usually depends on what you're storing in the arrays and how you're accessing them...

If there are logical groupings/sets and you'd ever want to loop through the arrays ($array1, $array2, etc...) then make them nested associative arrays.

$Config = array(
    'Database' => array(
        'Host'=>"10.0.0.1",
        'user'=>"root"
    ),
    'API' => array(
        'Endpoint'=>"http://example.com/"
    ),
);

If they're totally different, then it's really a judgement call

An array of arrays may be marginally lighter on memory but to be honest, with PHP the difference is going to be so small, it's not really worth wasting time worrying about until you get a performance bottleneck - and when you do, I suspect it won't be with how you declare your arrays

Upvotes: 6

Erwin Moller
Erwin Moller

Reputation: 2408

The second one will be slightly "better" since it doesn't create multiple variablenames.

Personally I wouldn't care and take the one that makes the most sense in your current situation. Style is often more important than performance, unless you have a compelling reason to focus on performance. (In which case another solution that PHP might be better.)

Upvotes: 1

bogatyrjov
bogatyrjov

Reputation: 5378

Kind of, if You'll have 1000 arrays, then it is probably better to have them all in one array, so using an array of arrays is better, then using 1000 variables each containing an array.

Upvotes: 2

Related Questions