Closure usage examples and execution efficiency test examples in PHP

Source: Internet
Author: User
This article mainly introduces the closure (anonymous function) in PHP, this paper gives a use of examples and execution efficiency test, the need for friends can refer to the following

Closures are also called anonymous function PHP5.3 introduced.

How to use

You need to adjust the values in the array elements

The code is as follows:

$data = Range (0, 100);//You want the value of each element to be appended with the. html suffix $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);//If you use foreach, you need to set the zero , assign the required value to the variable

Execution efficiency

The code is as follows:

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

After 5W execution, from the results of 1-3, most of the time the execution times are increased, one of the results of the execution time is as follows

The code is as follows:

1:0.02600097656252:0.0380020141601563:0.047003030776978

Conclusion

The code for closures is relatively elegant, but logic is easier to confuse and less efficient to implement than other methods, so use caution. It is recommended to use when the code structure is messy and needs to be encapsulated.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.