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

伊谢尔伦
Release: 2023-03-12 09:50:01
Original
1344 people have browsed it

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);
Copy after login

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还需要在循环里面建立零时变量,把需要的值赋给这个变量
Copy after login

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);
Copy after login

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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template