gpt4 book ai didi

php - 静态变量和函数 : memory allocation in php

转载 作者:可可西里 更新时间:2023-10-31 23:48:43 26 4
gpt4 key购买 nike

我对 php 5.3 脚本的内存分配有疑问。假设您有 2 个静态类(MyData 和 Test),如下所示:

class MyData {
private static $data = null;

public static function getData() {
if(self::$data == null)
self::$data = array(1,2,3,4,5,);
return self::$data;
}
}

class Test {
private static $test_data = null;

public static function getTestData1() {
if(self::$test_data==null) {
self::$test_data = MyData::getData();
self::$test_data[] = 6;
}
return self::$test_data;
}

public static function getTestData2() {
$test = MyData::getData();
$test[] = 6;
return $test;
}
}

还有一个简单的 test.php 脚本:

for($i = 0; $i < 200000; $i++) {
echo "Pre-data1 Test:\n\t" . memory_get_usage(true) . "\n";
Test::getTestData1();
echo "Post-data1 Test:\n\t" . memory_get_usage(true) . "\n";
}

for($i = 0; $i < 200000; $i++) {
echo "Pre-data2 Test:\n\t" . memory_get_usage(true) . "\n";
Test::getTestData2();
echo "Post-data2 Test:\n\t" . memory_get_usage(true) . "\n";
}

我可能假设调用 Test::getTestData1() 将为 2 个静态变量分配内存,而 Test::getTestData2() 将在函数返回时销毁 $test(静态变量的副本),因此第二个调用不那么“内存昂贵”。

但是如果我运行 test.php 脚本,memory_get_usage 将为 Test::getTestData1() 和 Test::getTestData2() 显示相同的值

为什么?

最佳答案

您正在以错误的方式测试内存使用情况。使用 memory_get_usage(false); 获取脚本实际使用的内存。memory_get_usage(true); 简单地返回系统分配的内存,这对于小脚本来说总是相同的。

关于php - 静态变量和函数 : memory allocation in php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17209700/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com