下面的代码是否存在内存泄漏?我们有一个使用PHP v5.3.3在Apache服务器上运行的网站,这个代码被批评为可能有内存泄漏。希望看到另一组眼睛有助于发现问题。
<?php
// set feed URL
$feedURL = 'http://gdata.youtube.com/feeds/api/users/UFDeptHousing/uploads';
// read feed into SimpleXML object
$sxml = simplexml_load_file($feedURL);
?>
<?php
// iterate over entries in feed
$i = 0;
foreach ($sxml->entry as $entry) {
if($i < 4) {
// get nodes in media: namespace for media information
$media = $entry->children('http://search.yahoo.com/mrss/');
// get video player URL
$attrs = $media->group->player->attributes();
$watch = $attrs['url'];
// get video thumbnail
$attrs = $media->group->thumbnail[1]->attributes();
$thumbnail = $attrs['url'];
// get <yt:duration> node for video length
$yt = $media->children('http://gdata.youtube.com/schemas/2007');
$attrs = $yt->duration->attributes();
$length = $attrs['seconds'];
// get <yt:stats> node for viewer statistics
$yt = $entry->children('http://gdata.youtube.com/schemas/2007');
$attrs = $yt->statistics->attributes();
$viewCount = $attrs['viewCount'];
// get <gd:rating> node for video ratings
$gd = $entry->children('http://schemas.google.com/g/2005');
if ($gd->rating) {
$attrs = $gd->rating->attributes();
$rating = $attrs['average'];
} else {
$rating = 0;
}
?>
<tr>
<td width="95">
<span class="thumbnail"><a href="<?php echo $watch; ?>"><img src="<?php echo $thumbnail;?>" width="85" height="48" alt="<?php
$varlength = strlen($media->group->title);
if ($varlength > 30) {
echo substr($media->group->title,0,30)."...";
}else {
echo $media->group->title;
} ?>" /></a></span>
</td>
<td width="130">
<span class="title"><a href="<?php echo $watch; ?>">
<?php
$varlength = strlen($media->group->title);
if ($varlength > 30) {
echo substr($media->group->title,0,30)."...";
}else {
echo $media->group->title;
} ?>
</a></span>
<span class="length">Length: <?php printf('%0.2f', $length/60); ?></span>
</td>
</tr>
<?php
}
$i++;
}
?>
答案 0 :(得分:2)
“此代码被批评为可能存在内存泄漏”
谁在批评?如果它是一个IDE,那么有可能它没有意识到所有数据收集都是在循环的上下文中完成的,这个循环将在4次迭代后停止收集数据。
也可能担心没有“其他”这一事实 - 即,如果我&gt; 4,它将继续循环直到它贯穿整个文件。它不会继续累积数据,但会继续循环。如果文件足够大,可能会导致问题。
但也许在“if”的末尾添加“else {break;}”会使错误消失。
答案 1 :(得分:0)
此代码的每次操作都会占用很少的内存:
Mem: 77920 / 77960
Mem: 83968 / 83968
Mem: 84280 / 84280
(RHEL5 / PHP 5.1.6)
但这是预期的。我没有发现使用unset这个代码有任何好处,但是你总是可以在函数中包含代码来解决所有问题。
使用memory_get_usage()
进行测试,测试和测试