我在PHP中将文件加载到数组中。我正在将文件加载到数组中,因为它是一个字典,我想利用二进制搜索来查找我的单词是否在字典中。由于那里有各种各样的信息,我尝试了这两种不同的方式。它们的时间非常相似,出于某种原因,我的1.1MB文件导致PHP使用20MB的内存。
方法1:
<?php
echo 'Memory Usage Start: ' . memory_get_usage() . '<br>';
$start = microtime(true);
$fs=fopen("./dictionary.txt", "r");
$dictionary=array();
while (!feof($fs)){
$dictionary[]=trim(fgets($fs));
}
$end = microtime(true);
echo 'Memory Usage End: ' . memory_get_usage() . '<br>';
echo 'Total Time: ' . ($end - $start) . ' seconds';
输出是:
Memory Usage Start: 5298144
Memory Usage End: 25254944
Total Time: 0.17744994163513 seconds
方法2:
<?php
echo 'Memory Usage Start: ' . memory_get_usage() . '<br>';
$start = microtime(true);
$dictionary = file('./dictionary.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$end = microtime(true);
echo 'Memory Usage End: ' . memory_get_usage() . '<br>';
echo 'Total Time: ' . ($end - $start) . ' seconds';
输出是:
Memory Usage Start: 5297240
Memory Usage End: 25244920
Total Time: 0.074188947677612 seconds
PHP中的数组似乎比我想象的要大得多。我想我能想到的一个解决方案是解析到文件的中间并读取该行,并以这种方式进行二进制搜索。但是,执行这么多文件读取来查找值似乎效率更低。
无论如何,我们将非常感激任何见解。