Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php open file performance

I have a question regarding php and opening files

PHP has more than one function to open files:

file_get_contents()
fopen()
file()

My question is related to performance. On my server I have to open files, then check the contents, do some modifications if I need to, and resave them.

I want to make these changes as fast as possible

which one is better to open file (both small and large) performance wise? Meaning; why use one in preferance to the others?

like image 277
Xin Qian Ch'ang Avatar asked Nov 21 '11 03:11

Xin Qian Ch'ang


1 Answers

file_get_contents() and file() both read the entire file into memory - difference being that one returns a string, while the other returns an array.

For small(ish) files, this may not be much of a performance hit for you.

For larger files, this can definitely make a tremendous impact. If the target file is of size 20MB, and you need to check a particular segment of data at some known distance into the file, fopen() and then seeking to that known position to get just the data you require would be much quicker, along the order of several magnitudes.

20MB is, of course, just an arbitrary number I pulled out of thin air, but consider that an arbitrarily large file just might exceed the resource usage limits imposed by your server upon your PHP environment.

like image 170
Christopher Avatar answered Sep 28 '22 14:09

Christopher