php - 降低 PHP 脚本的内存使用量?
问题描述
因此,我从 API 端点获取数据并将其添加到我已经拥有的 CSV 文件的末尾,然后重新编写 CSV(这是必需的,因为稍后我需要为我从中提取的每个端点提供日志) .
我是 PHP 新手,不太确定降低内存使用率的最佳方法。我环顾四周,但对我来说没有什么特别突出的。
在下面的具体示例中,CSV 文件中有大约 100,000 行。
按照运行脚本时的 memory_get_usage 顺序,我得到了 58982400、103546880、103546880。我想降低使用的内存。在尝试降低使用的内存时,是否有任何提示或事项需要我注意?看起来有 1/2 的内存被用于从端点获取数据,我认为对于这种使用我无能为力?
来自 CSV 的数据基本上是
PersonId,FirstName,LastName,Gender
虽然来自端点的数据是
PersonId,EmailAddress
这是我的脚本。
<?php
include('ApiClient.include.php');
$urlStudents = "http://localhost/jsonyes.json";
$crl = curl_init();
curl_setopt($crl, CURLOPT_URL, $urlStudents);
curl_setopt($crl, CURLOPT_RETURNTRANSFER, 1);
$execCrl = curl_exec($crl);
$emails = json_decode($execCrl, true);
curl_close($crl);
$fp = fopen('turkeytest.csv', 'r');
$output = fopen("$emailFile", 'w');
$max = 0;
echo "Using GetUse ", memory_get_usage(True), " bytes of ram.";
foreach($emails as $email){
if(!isset($eData[$email['PersonId']])){
$eData[$email['PersonId']][] = $email['EmailAddress'];
} else{
$eData[$email['PersonId']][] = $email['EmailAddress'];
}
if(count($eData[$email['PersonId']]) > $max){
$max = count($eData[$email['PersonId']]);
}
}
echo "Using GetUse ", memory_get_usage(True), " bytes of ram.";
while($row = fgetcsv($fp, ",")){
$count = count($row);
if(isset($eData[$row[0]])){
foreach($eData[$row[0]] as $key => $value){
$row[] = $value;
}
}
$row = array_pad($row, $max+$count, '');
fputcsv($output, $row); //writes array $datas to $output file
}
fclose($fp);
echo "Using GetUse ", memory_get_usage(True), " bytes of ram.";
?>
解决方案
推荐阅读
- regex - 什么是拆分句子但排除某些特定情况的正则表达式
- compression - 用于压缩的二元决策图等工具
- excel - VBA,excel:删除/插入行,没有错误,没有结果
- c# - AddorUpdate 字典中的数据
- python - Pytest隐藏了一些参数值
- selenium-webdriver - selenium c# 边缘浏览器:'意外错误。未知错误'
- r - 将列添加到数据框中
- spring-boot - 使用接口投影方法名称呈现结果集列名称时出现问题 - 从多个表中获取多个列
- conda - conda 使用更新版本的 glibc
- python - 在python中根据名称和时间聚合数据