Memory / optimization issues
I am working on a complex script that can handle up to 500,000 records. Here's my question.
Basically my code will parse a text file to get each of those 500,000 or so records. Each entry will have a category, my code will have to check if a new table entry was categories
created for that category during that particular processing, and if not, it will create that entry.
So I have 2 options:
1) I am storing an array of keys => values containing the category name and ID, so I could do this:
if (array_key_exists($category,$allCategories))
$id=$allCategories[$category];
else
{
mysql_query("INSERT INTO categories (procId,category)
VALUES ('$procId''$category')");
$id=mysql_insert_id();
$allCategories[$category]=$id;
}
2) Every time this text file is processed it gets its own process ID. So instead of checking for a variable $allCategories
that might grow to have 100,000 entries, I could do this:
SELECT id FROM categories WHERE procId='$procId' AND category='$category'
The downside here is that this query will run for each of the 500,000+ records. Whereas the disadvantage of storing all categories in an array is that I might lose memory or the server might crash.
Any thoughts?
a source to share
Can you just keep a list of the ids you have already inserted? If they are integer identifiers, then 4 bytes each time 100,000 entries will only use about 400 KB of memory.
ETA:
To avoid storing the category name, enter the name and save the hash. With a 128-bit MD5 hash, that's 16 bytes per hash, or only about 1.6MB of memory + overhead.
a source to share