开发者

fastest way to see if a string is found in a file?

Let's say I have a big file. The file is a list of IPs each on a new line like this:

123.123.123.123
123.123.123.124
123.123.123.125
etc...

I could do it like this:

$file = file_get_contents($src);    
if (substr_count($file,'myip'))
    echo 'FOUND';

Or a similar way with array style:

$file = file($src,FILE_IGNORE_NEW_LINES);
if (in_array('myip',$file))
    echo 'FOUND';

But I think there is a third alternative that could be faster.

Parsing the file line by line and of course stopping the reading if the string is found.

Something like this:

$file = fopen($src,'r');
while(!feof($file)) { 
    $ip = fgets($file);
    if ($ip == $myIP) {
        die('Found');
    }   
}
fclose($file);

My question is: do you think there are other better way?

And performance-wise which code do you think is faster?

开发者_Go百科Thanks a lot guys


If you can, consider using grep or find. It might be faster and, more importantly, more memory-efficient than PHP.


Assuming doing this in a language is a requirement, a modification of your line-by-line code would probably be best, so you're not grabbing any more data than you need.

$file = fopen($src,'r');
while(!feof($file)) { 
    $ip = fgets($file);
    if ($ip == $myIP) {
        echo 'FOUND!';
        break; // dieing here won't close the file
    }   
}

fclose($file);


If you could keep the file sorted, then performing a binary search would perform well.

However, sorting the file will take some time, so if you are doing a lot of inserts/deletes it might not be very effective.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜