内存泄漏也称作“存储渗漏”,用动态存储分配函数动态开辟的空间,在使用完毕后未释放,结果导致一直占据该内存单元。直到程序结束。即所谓内存泄漏。
1.如果PHP对象存在递归引用,就会出现内存泄漏。这个Bug在PHP里已经存在很久很久了,先让我们来重现这个Bug,代码如下:
<?php
class Foo {
function __construct() {
$this->bar = new Bar($this);
}
}
class Bar {
function __construct($foo) {
$this->foo = $foo;
}
}
for ($i = 0; $i < 100; $i++) {
$obj = new Foo();
unset($obj);
echo memory_get_usage(), "\n";
}
?>
运行以上代码,你会发现,内存使用量本应该不变才对,可实际上却是不断增加,unset没有完全生效。
现在的开发很多都是基于框架进行的,应用里存在复杂的对象关系,那么就很可能会遇到这样的问题,下面看看有什么权宜之计:
<?php
class Foo {
function __construct() {
$this->bar = new Bar($this);
}
function __destruct() {
unset($this->bar);
}
}
class Bar {
function __construct($foo) {
$this->foo = $foo;
}
}
for ($i = 0; $i < 100; $i++) {
$obj = new Foo();
$obj->__destruct();
unset($obj);
echo memory_get_usage(), "\n";
}
?>
办法有些丑陋,不过总算是对付过去了。幸运的是这个Bug在PHP5.3的CVS代码中已经被修复了。
1.如果PHP对象存在递归引用,就会出现内存泄漏。这个Bug在PHP里已经存在很久很久了,先让我们来重现这个Bug,代码如下:
<?php
class Foo {
function __construct() {
$this->bar = new Bar($this);
}
}
class Bar {
function __construct($foo) {
$this->foo = $foo;
}
}
for ($i = 0; $i < 100; $i++) {
$obj = new Foo();
unset($obj);
echo memory_get_usage(), "\n";
}
?>
运行以上代码,你会发现,内存使用量本应该不变才对,可实际上却是不断增加,unset没有完全生效。
现在的开发很多都是基于框架进行的,应用里存在复杂的对象关系,那么就很可能会遇到这样的问题,下面看看有什么权宜之计:
<?php
class Foo {
function __construct() {
$this->bar = new Bar($this);
}
function __destruct() {
unset($this->bar);
}
}
class Bar {
function __construct($foo) {
$this->foo = $foo;
}
}
for ($i = 0; $i < 100; $i++) {
$obj = new Foo();
$obj->__destruct();
unset($obj);
echo memory_get_usage(), "\n";
}
?>
办法有些丑陋,不过总算是对付过去了。幸运的是这个Bug在PHP5.3的CVS代码中已经被修复了。
2.php的json_encode函数问题
在公司做了一个应用,是php与c++进行网络交互,所以选择了json这种比较通用的序列化格式,然而却遇到了比较奇怪的问题。
先来看如下代码(php):
1 2 3 4 5 | $objs = array(); $objs[1] = 'a'; $objs[2] = 'b'; $objs[4] = 'd'; echo json_encode($objs)."\n"; |
输出的结果如下:
{"0":"a","1":"b","3":"d"}
这样是正常的,用jsoncpp也可以正确的解析出来,php自动将$objs当作一个关联数组来生成json数据了。
然而当把代码换成如下:
1 2 3 4 5 6 | $objs = array(); $objs[0] = 'a'; $objs[1] = 'b'; $objs[2] = 'c'; $objs[3] = 'd'; echo json_encode($objs)."\n"; |
则输出结果如下:
["a","b","c","d"]
jsoncpp按照之前的解析方法是解析不出来的~
其实对php来说,这也是合理的,问题在于在php里面普通数组和关联数组都是array,而对c++来说,却存在vector和map之分,所以如果还是想要json_encode生成关联数组的格式,那么需要这样写:
1 2 3 4 5 6 | $objs = array(); $objs[0] = 'a'; $objs[1] = 'b'; $objs[2] = 'c'; $objs[3] = 'd'; echo json_encode((object)$objs)."\n"; |
结果如下:
{"0":"a","1":"b","2":"c","3":"d"}