Home >Backend Development >PHP Tutorial >Detailed explanation of closure usage examples and execution efficiency test examples in PHP

Detailed explanation of closure usage examples and execution efficiency test examples in PHP

伊谢尔伦
伊谢尔伦Original
2017-07-01 13:06:461356browse

This article mainly introduces a brief analysis of closures (anonymous functions) in PHP. This article gives a usage example and execution efficiency test. Friends in need can refer to it

Closure is also called anonymous function introduced in PHP5.3.

Usage method

Need to adjust the value in the integergroup element

The code is as follows:

$data = range(0, 100);//想要每个元素的值都加上.html的后缀
$suffix = '.html';
function makeSuffix($str, $suffix)
{
    return $str . $suffix;
}
$new_data = array_map(function($item) use ($suffix) {
    return makeSuffix($item, $suffix);
}, $data);

Need to change the structure of the element

The code is as follows:

$arr = [
    [
        'id'=>'',
        'name'=>'',
        'create_time'=>'',
    ],
];
$new_data = array_map(function($item) {
    return ['id'=>$item['id'],'name'=>$item['name']];
}, $arr);
//如果是用foreach还需要在循环里面建立零时变量,把需要的值赋给这个变量

Execution efficiency

The code is as follows:

$data = range(0, 50000)
//1
foreach ($data as &$value) {
    $value = makeSuffix($value, $suffix);
}
//2
foreach ($data as $value) {
    $new[] = makeSuffix($value, $suffix);
}
//3
array_map(function($item) use ($suffix) {
    return makeSuffix($item, $suffix);
}, $data);

After 5W executions, looking at the results 1-3, the execution time increases in most cases. One of the execution result times is as follows

The code is as follows:

1:0.0260009765625
2:0.038002014160156
3:0.047003030776978

Conclusion

The closure code is relatively elegant, but the logic is easy to confuse, and the execution efficiency is relatively low compared to other methods, so it should be used with caution. It is recommended to use it when the code structure is messy and needs to be encapsulated.

The above is the detailed content of Detailed explanation of closure usage examples and execution efficiency test examples in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn