技术开发 频道

使用PHP 5.2 中新的内存管理器

    清单 5 是在任何位置都可能使用的简单 MySQL 数据库操作。在运行脚本时,我们注意到一些与内存使用量相关的奇怪行为并需要将其检查出来。为了使用内存管理函数以使我们可以检验发生错误的位置,我们将使用以下代码。

清单 6. 定标查找错误的示例
<?php if( !function_exists('memory_get_usage') ){ include('function.php'); } echo "At the start we're using (in bytes): ", memory_get_usage() , "\n<br>"; $db = mysql_connect("localhost", "user", "password"); mysql_select_db("memory_test"); echo "After connecting, we're using (in bytes): ", memory_get_usage(),"\n<br>"; for ( $x=0; $x<10; $x++ ) { $sql = "SELECT data FROM leak_test WHERE id='".$x."'"; $result = mysql_query($sql); // The operation // suspected of leaking. echo "After query #$x, we're using (in bytes): ", memory_get_usage(), "\n<br>"; mysql_free_result($result); echo "After freeing result $x, we're using (in bytes): ", memory_get_usage(), "\n<br>"; } mysql_close($db); echo "After closing the connection, we're using (in bytes): ", memory_get_usage(), "\n<br>"; echo "Peak memory usage for the script (in bytes):". memory_get_peak_usage(); ?>

    注:按照定义的时间间隔检查当前内存使用量。在下面的输出中,通过显示我们的脚本一直在为函数分配内存,并且在应当释放的时候没有释放内存,从而提供对内存泄露的实际测试,您可以看到每次调用时内存使用量如何增长。

清单 7. 测试脚本输出

At the start we're using (in bytes): 63216 After connecting, we're using (in bytes): 64436 After query #0, we're using (in bytes): 64760 After freeing result 0, we're using (in bytes): 64828 After query #1, we're using (in bytes): 65004 After freeing result 1, we're using (in bytes): 65080 After query #2, we're using (in bytes): 65160 After freeing result 2, we're using (in bytes): 65204 After query #3, we're using (in bytes): 65284 After freeing result 3, we're using (in bytes): 65328 After query #4, we're using (in bytes): 65408 After freeing result 4, we're using (in bytes): 65452 After query #5, we're using (in bytes): 65532 After freeing result 5, we're using (in bytes): 65576 After query #6, we're using (in bytes): 65656 After freeing result 6, we're using (in bytes): 65700 After query #7, we're using (in bytes): 65780 After freeing result 7, we're using (in bytes): 65824 After query #8, we're using (in bytes): 65904 After freeing result 8, we're using (in bytes): 65948 After query #9, we're using (in bytes): 66028 After freeing result 9, we're using (in bytes): 66072 After closing the connection, we're using (in bytes): 65108 Peak memory usage for the script (in bytes): 88748

    我们所做的操作是发现了执行脚本时出现的一些可疑操作,然后调整脚本使其给我们提供一些可理解的反馈。我们再次运行了脚本,在每次迭代期间使用 memory_get_usage() 查看内存使用量的变化。根据分配的内存值的增长情况,暗示了我们用脚本在某个位置建立了一个漏洞。由于 mysql_free_result() 函数不释放内存,因此我们可以认为 mysql_query() 并未正确分配内存。

结束语

    PHP V5.2 版包括一些优秀的新工具,可以帮助您更好地洞察脚本的系统内存分配情况,以及重新全面控制内存管理的精确调整。当得到有效使用时,新内存管理工具将支持您的调试工作,从而重新获得一些系统资源。

0
相关文章