Can PHP’s unset() function improve performance?

Asked

Viewed 2,583 times

9

I think the answer to my question would be "yes." even because I end up doing it in my code (when I remember), but I just stopped to think about it now and I’m kind of worried if someone asked me about it, I wouldn’t know how to answer the "why" of it satisfactorily.

Follow an example from:

<?php
# aqui um array multidimensional com 10k de linhas
$data  = array(...);
# aqui peguei o que eu precisava da variável acima
$total = (int) count($data); 
# a partir de agora não preciso mais usar a variável $data
?>

From the line I no longer need to use a variable in the rest of the code, I need to delete it using the unset($data) as in what I mentioned above? Does this bring any improvement in performance in fact? 'Cause I think the same processing that would have to load it itself without using it, would be the processing of erasing it.

  • 1

    Just remembering that the unset() is not a function, but a language constructor. See here the list.

4 answers

10


It depends on the context because if it is misapplied cause opposite effect, increasing the use of memory and processing.

See a simple test:

Test 1

Here we use unset() to remove variable indexes $arr 1 for 1.
The logic here is that we are already making an iteration in each of the indexes so theoretically it could be more performative already to remove each one, right?

$arr = range(1, 100000);
foreach ($arr as $k => $v) {
    if ($k % 2 === 0) {
        $arr2[] = $v;
    }
    unset($arr[$k]);
}

The result of memory usage:

Pico: 17174288 (17mb)
Chain: 10883880 (10mb)

Execution time (microseconds)

Total: 0.0090339183807373
Initial: 1469910070.9007
Ending: 1469910070.9097




Test 2

In this second test, we think of a different way. Starting from the logic that every time unset() is invoked, would be consuming more memory and processing. As the ultimate goal is to completely erase the variable $arr then we can do it by invoking unset() only 1 time, after repeat loop.

$arr = range(1, 100000);
foreach ($arr as $k => $v) {
    if ($k % 2 === 0) {
        $arr2[] = $v;
    }
}
unset($arr);

The result of memory usage:

Pico: 10882752 (10mb)
Chain: 4592344 (4mb)

Execution time (microseconds)

Total: 0.0061979293823242
Initial: 1469910142.5007
Ending: 1469910142.5069

Here we draw a conclusion that the theory of the second test is correct for the context presented here. Repeated invocation of the function unset(), within the context of the test, cause opposite effect, impairing performance significantly.

The running time presents a "negligible" difference of 0.003 micro seconds for human perception, however, it is a relevant difference in terms of data processing. But what draws attention the most is the memory consumption. The function unset() can rather improve performance by freeing space in memory in significant way when used appropriately.

General rule:

  1. Repeated invocation of a function generates greater consumption.
  2. Applique unset() objects that will no longer be used, especially if there are still more routines to be performed. It will save memory for the rest of the processes.

Garbage collector?

We can argue that it is "unnecessary" to be careful because at the end of all processes, everything "dies", but depending on the context it is always good to free up space in memory.

PHP has a memory usage limiter, defined in the settings (php.ini). Normally the default is between 64mb and 128mb. A script that reaches half the processing already consuming 125mb, for example, has a great risk of causing execution interruption due to lack of memory. Many of these "out of memory" cases could be avoided if the script cleaned the variables that are not being used. Therefore, it is very valid to be careful to free up memory space during executions.





Terms used
peak: largest amount of space used during execution, i.e., the "memory peak"

current: amount of memory being used right after unset()

initial and final: the initial time and the final time of the execution in timestamp format, using the microtime function()

total: is the calculation of the difference between the initial time and the final time in microseconds.

  • Peak, current, total, initial, final would be what specifically, I’m sorry I’m a half layman?

  • 1

    I added at the end of the answer the meaning of these terms.

7

In fact it is highly unlikely that you will get some performance gain.

This command says that the variable will no longer be used. This does not increase performance. It even consumes a minimum to say this.

One might think there will be a gain because the memory is released. This could even be true in very specific circumstances, where you have a large memory constraint and the application runs for a long time, which is rare in PHP. But it is not because the function even releases memory. At most it allows the release to be made.

So it would be true in some case, but I would need to analyze it concretely with real code and structure that it will run.

If you find a situation that performance is important and there is clear indication (you have to measure) that memory consumption is forcing code to do swap on disk, then it may be interesting to give this solution.

At least from a performance point of view, if you don’t prove that the command achieves a necessary (real) result, don’t waste time with it.

  • I remember that I became aware of this when a script was not run for lack of memory, it always appeared memory limit exceeded even using all existing on the server, so in the hope of solving the problem by trying everything possible, I ended up using unset() in the belief that some benefit brought, and in my case, in this specific and rare worked, in others, none, as well as you quoted.

1

The builder unset(), does not have much effect or impact on the performance itself, but can improve performance, over a process that is being used later, such as session use for example, if you think globally, you will be eliminating data in the process, which would eliminate resources and memory, however, will be running a new process for that that will use memory, but very little, nothing that will effectively impact the process. Unless it’s misused as Daniel explains.

1

Hello,

your amount of free memory will have no effect on the performance of your PHP programs. You will only have more space to allocate memory by creating more variables.

Even in a situation where you consume all available memory, this would not have an impact on performance since the PHP interpreter limits the amount of memory that can be consumed by a process preventing it from degrading the system.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.