What's better at freeing memory with PHP: unset() or $var = null

前端 未结 13 2224
陌清茗
陌清茗 2020-11-22 08:57

I realise the second one avoids the overhead of a function call (update, is actually a language construct), but it would be interesting to know if one is be

13条回答
  •  庸人自扰
    2020-11-22 09:31

    Regarding objects, especially in lazy-load scenario, one should consider garbage collector is running in idle CPU cycles, so presuming you're going into trouble when a lot of objects are loading small time penalty will solve the memory freeing.

    Use time_nanosleep to enable GC to collect memory. Setting variable to null is desirable.

    Tested on production server, originally the job consumed 50MB and then was halted. After nanosleep was used 14MB was constant memory consumption.

    One should say this depends on GC behaviour which may change from PHP version to version. But it works on PHP 5.3 fine.

    eg. this sample (code taken form VirtueMart2 google feed)

    for($n=0; $n" . memory_get_usage() . "";//$ids[$n];
            time_nanosleep(0, 10000000);
        }
    
        $product = $productModel->getProductSingle((int)$ids[$n],true, true, true);
        ...
    

提交回复
热议问题