Closures or create_function in PHP

大兔子大兔子 提交于 2019-11-30 16:22:20

The construct function() {..} is an anonymous function, and this feature is often implemented together with closures. Neither create_function nor anonymous functions pollute the global namespace.

Since anonymous functions can access surrounding variables (the closure part), they can, in theory, be slightly slower. On the other hand, if you're using bytecode caching (and if you're not, you are obviously not concerned about performance), I'd expect the "compilation" overhead of anonymous functions to be slightly slower.

However, it is extremely unlikely that the difference between anonymous functions and create_function is a source of performance problems. Therefore, I'd choose the more readable form of an anonymous function if you are so fortunate to have a target platform with php>5.3.

create_function creates a global function that persists for the rest of the program. create_function simply returns the function name (a string), and therefore can have no idea if you still have access to that name stored somewhere somehow or not. Therefore, it can't be "garbage collected", even if you don't have access to the name anymore.

That means that a big problem is if you create a lot of functions using create_function, it will cause your program to run out of memory:

for ($i = 0; $i < 1000000; $i++) {
  $f = create_function('', '');
  // do stuff

  // don't use $f anywhere after this point
}

whereas with anonymous functions, that won't happen (the closure will be garbage collected).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!