faster fopen or file_get_contents?

22,379

Why dont you cache the image content with apc ?

if(!apc_exists('img_'.$id)){
    apc_store('img_'.$id,file_get_content(...));
}

echo apc_fetch('img_'.$id);

this way image content will not be read from your disk more than once.

Share:
22,379
Rami Dabain
Author by

Rami Dabain

Wheres my coffee?

Updated on July 29, 2020

Comments

  • Rami Dabain
    Rami Dabain almost 4 years

    i am running multiple websites with high traffic , as a requirement , all images are downloaded via image.php?id=IMAGE_ID_HERE . If you ever done that before , you know that that file will be reading the file image and echoing it to the browser with special headers .

    My problem is , the load on the server is very high (150-200) and TOP command shows multiple instances of image.php , so image.php is running slow !

    the problem probably is fopen loading the image to the memory before sending it to the client. How to read a file and pass it through directly?

    Thank you guys


    UPDATE

    After you optimized the code, used caching wherever possible, do create a CDN . couple of servers, sync methods, load balancers and no need to worry about requests anymore :)

  • Admin
    Admin over 12 years
    apc is hard to setup correctly. but it could be a good solution!
  • Paté
    Paté over 12 years
    Well if the website as lots of hits than I/O on disk is high due to concurent file_get_contents, storing the content in ram would get rid of that
  • Admin
    Admin over 12 years
    @Col.Shrapnel reading from Memory is faster than reading from Disk
  • Your Common Sense
    Your Common Sense over 12 years
    there is not a sign of the I/O peak in the question. Go figure. It clearly says that it's CPU utilization above the limits.
  • Paté
    Paté over 12 years
    In my experience lots of I/O is never good for load performance. If this guy has a load of 200 on this particular script than he has high IO because of the way the file are served. I'm not saying it will fix his issues but It's worth a shot IMO.
  • Rami Dabain
    Rami Dabain over 12 years
    if you're getting like 5000 image requests/second , that would be a problem for the memory if APC is memory-based cache !!! specially if you have thousands of images !!!
  • Paté
    Paté over 12 years
    I believe the issue is not the number of requests / seconds but more the size of all the images, you could also couple that with a RoundRobin solution. I know facebook uses memcache to cache some of their profile image so there is a reason why...
  • Rami Dabain
    Rami Dabain over 11 years
    with the 5000 images /second ... i meant deferent images not the same , otherwise i would have cached them