user1242440
user1242440

Reputation: 31

$data = array() vs unset($array)

this is my first question.

I am doing some optimizations on a php script, improving its speed of execution...

Between :

$datas = array();
$datas['file_import'] = $file_name_reporting;

And :

unset($datas);
$datas['file_import'] = $file_name_reporting;

Can someone tell me which one is faster ?

Thank you

Upvotes: 3

Views: 1109

Answers (6)

Eugene Manuilov
Eugene Manuilov

Reputation: 4361

Obviously the first code will work faster because you do only two operations: explicitly create an array and add a portion of data. The second example will cause a warning because you destroy a variable and then try to use it again.

Additionally unset will not release used memory, it will only release a pointer on variable. Memory will be released when gc will be runned. To release a memory, use $datas = null; instead.

Upvotes: 1

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76413

In both cases, a new Array will be constructed. Unsetting a variable in php, will set it's value to null, only to call the array constructor on the next line. Although I agree with knittl, my suggestion would be:

$datas = array('file_import' => $file_name_reporting);

By creating a new array, you automatically 'unset' the variable, and by passing values to the array constructor, you can fill your array with whatever values you want while you're at it.

Upvotes: 1

Jon
Jon

Reputation: 437544

It's ridiculous to claim that either form is "faster" than the other. Both versions will execute so fast that you would need to run them millions of times inside a loop to perhaps notice a difference. Do you actually do that inside your script? If not, forget about "optimization" here (actually, it would be a good idea to forget about all optimization "by eye", as any experienced developer can tell you).

On top of that, the two versions actually do different things, in that unset will remove the name $datas from the sumbol table (and give you a notice in the next line when you attempt to add a value to an array).

Just use what feels right, and look inside heavy loops to find something to optimize.

Upvotes: 1

AHHP
AHHP

Reputation: 3047

I think first method is just a overwriting but second one includes deleting, checking existence, triggering warning and creating new array

Upvotes: 1

cool.ernest.7
cool.ernest.7

Reputation: 93

array() will create an array whereas unset() will destroy a variable.

Upvotes: 1

hsz
hsz

Reputation: 152266

Your second example causes warning, because $datas is right now null and you are treating it as an array, so you have to declare it as an empty array before.

So just follow your first example - assign an empty array and then put into it some data.

Upvotes: 3

Related Questions