สวัสดีตอนเช้า ฉันกำลังเรียนบทเรียนหนักๆ ขณะพยายามจัดการไฟล์ CSV ขนาดใหญ่สูงสุด 4GB
เป้าหมายคือการค้นหาบางรายการในไฟล์ csv (ฟีดข้อมูลของ Amazon) โดย browsernode ที่ระบุและโดยบางรายการ id's (ASIN) เพื่อให้ได้การผสมผสานระหว่างรายการที่มีอยู่ (ในฐานข้อมูลของฉัน) บวกกับรายการใหม่เพิ่มเติม เนื่องจากรายการหายไปในตลาดเป็นครั้งคราว ฉันยังกรองชื่อของรายการเนื่องจากมีหลายรายการที่ใช้เหมือนกัน
ฉันได้อ่านเคล็ดลับต่างๆ มากมายที่นี่ และในที่สุดก็ตัดสินใจใช้ fgetcsv() ของ php และคิดว่าฟังก์ชันนี้จะไม่ทำให้หน่วยความจำหมด เนื่องจากมันจะอ่านไฟล์ทีละบรรทัด แต่ไม่ว่าฉันจะพยายามทำอะไร ความทรงจำของฉันก็จะหมดอยู่เสมอ ฉันไม่เข้าใจว่าทำไมรหัสของฉันจึงใช้หน่วยความจำมาก
ฉันตั้งค่าขีดจำกัดหน่วยความจำเป็น 4096MB ขีดจำกัดเวลาคือ 0 เซิร์ฟเวอร์มี RAM 64 GB และฮาร์ดดิส SSD สองตัว
ใครก็ได้โปรดตรวจสอบโค้ดของฉันและอธิบายว่าเป็นไปได้อย่างไรที่หน่วยความจำของฉันหมดและสำคัญกว่านั้นคือการใช้หน่วยความจำอย่างไร
private function performSearchByASINs()
{
$found = 0;
$needed = 0;
$minimum = 84;
if(is_array($this->searchASINs) && !empty($this->searchASINs))
{
$needed = count($this->searchASINs);
}
if($this->searchFeed == NULL || $this->searchFeed == '')
{
return false;
}
$csv = fopen($this->searchFeed, 'r');
if($csv)
{
$l = 0;
$title_array = array();
while(($line = fgetcsv($csv, 0, ',', '"')) !== false)
{
$header = array();
if(trim($line[6]) != '')
{
if($l == 0)
{
$header = $line;
}
else
{
$asin = $line[0];
$title = $this->prepTitleDesc($line[6]);
if(is_array($this->searchASINs)
&& !empty($this->searchASINs)
&& in_array($asin, $this->searchASINs)) //search for existing items to get them updated
{
$add = true;
if(in_array($title, $title_array))
{
$add = false;
}
if($add === true)
{
$this->itemsByASIN[$asin] = new stdClass();
foreach($header as $k => $key)
{
if(isset($line[$k]))
{
$this->itemsByASIN[$asin]->$key = trim(strip_tags($line[$k], '<br><br/><ul><li>'));
}
}
$title_array[] = $title;
$found++;
}
}
if(($line[20] == $this->bnid || $line[21] == $this->bnid)
&& count($this->itemsByKey) < $minimum
&& !isset($this->itemsByASIN[$asin])) // searching for new items
{
$add = true;
if(in_array($title, $title_array))
{
$add = false;
}
if($add === true)
{
$this->itemsByKey[$asin] = new stdClass();
foreach($header as $k => $key)
{
if(isset($line[$k]))
{
$this->itemsByKey[$asin]->$key = trim(strip_tags($line[$k], '<br><br/><ul><li>'));
}
}
$title_array[] = $title;
$found++;
}
}
}
$l++;
if($l > 200000 || $found == $minimum)
{
break;
}
}
}
fclose($csv);
}
}