非静态闭包

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?php
class Foo {
protected $array;

public function __construct() {
$this->array = array_fill(0, 2000, 17);
}

public function getItemProcessor(): Closure {
return function () {
// do some processing unrelated to $this
};
}
}

$start = microtime(true);
$processors = [];
for ($i = 0; $i < 2000; $i++) {
$foo = new Foo();
$processors[] = $foo->getItemProcessor();
}

$memory = memory_get_usage() >> 20;
$time = (microtime(true) - $start) * 1000;
printf("This took %dms and %dMB of memory\n", $time, $memory);

执行结果:This took 77ms and 135MB of memory

静态闭包

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?php
class Foo {
protected $array;

public function __construct() {
$this->array = array_fill(0, 2000, 17);
}

public function getItemProcessor(): Closure {
return static function () {
// do some processing unrelated to $this
};
}
}

$start = microtime(true);
$processors = [];
for ($i = 0; $i < 2000; $i++) {
$foo = new Foo();
$processors[] = $foo->getItemProcessor();
}

$memory = memory_get_usage() >> 20;
$time = (microtime(true) - $start) * 1000;
printf("This took %dms and %dMB of memory\n", $time, $memory);

执行结果:This took 29ms and 2MB of memory

结果

  • 不管是在时间还是内存占用上用 static 修饰的闭包都要比未修饰的闭包要更