[英]C++ map lookup performance vs PHP array lookup performance
我無法理解以下內容,希望有人能為我提供一些幫助:
在C ++中,如果我創建一個包含2M個不同文本位(testdata)的測試數據向量,然后使用這些字符串作為索引值創建一個映射,然后查找所有值,如下所示:
//Create test data
for(int f=0; f<loopvalue; f++)
{
stringstream convertToString;
convertToString << f;
string strf = convertToString.str();
testdata[f] = "test" + strf;
}
time_t startTimeSeconds = time(NULL);
for(int f=0; f<2000000; f++) testmap[ testdata[f] ] = f; //Write to map
for(int f=0; f<2000000; f++) result = testmap[ testdata[f] ]; //Lookup
time_t endTimeSeconds = time(NULL);
cout << "Time taken " << endTimeSeconds - startTimeSeconds << "seconds." << endl;
這需要10秒鍾。
如果我似乎至少在PHP中做過同樣的事情:
<?php
$starttime = time();
$loopvalue = 2000000;
//fill array
for($f=0; $f<$loopvalue; $f++)
{
$filler = "test" . $f;
$testarray[$filler] = $f;
}
//look up array
for($f=0; $f<$loopvalue; $f++)
{
$filler = "test" . $f;
$result = $testarray[$filler];
}
$endtime = time();
echo "Time taken ".($endtime-$starttime)." seconds.";
?>
...僅需3秒。
既然PHP是用C編寫的,那么有誰知道PHP如何實現這種更快的文本索引查找?
謝謝C
您的循環不是絕對等價的算法。 請注意,在C ++版本中,
在PHP版本中,您只需在第一個循環中插入,然后在第二個循環中查找。
解釋了PHP-通常,如果您使用PHP編寫代碼更快,請先檢查代碼! ;-)
我懷疑您基准測試錯誤。 無論如何,我使用了您的代碼(必須對您的數據類型進行一些假設),這是我的計算機的結果:
PHP:花費2秒。
C ++(使用std :: map):耗時3秒。
C ++(使用std :: tr1 :: unordered_map):耗時1秒。
用C ++編譯
g++ -03
這是我的測試C ++代碼:
#include <map>
#include <sstream>
#include <string>
#include <vector>
#include <iostream>
#include <tr1/unordered_map>
int main(){
const int loopvalue=2000000;
std::vector<std::string> testdata(loopvalue);
std::tr1::unordered_map<std::string, int> testmap;
std::string result;
for(int f=0; f<loopvalue; f++)
{
std::stringstream convertToString;
convertToString << f;
std::string strf = convertToString.str();
testdata[f] = "test" + strf;
}
time_t startTimeSeconds = time(NULL);
for(int f=0; f<loopvalue; f++) testmap[ testdata[f] ] = f; //Write to map
for(int f=0; f<loopvalue; f++) result = testmap[ testdata[f] ]; //Lookup
time_t endTimeSeconds = time(NULL);
std::cout << "Time taken " << endTimeSeconds - startTimeSeconds << "seconds." << std::endl;
}
結論:
您測試了未優化的C ++代碼,甚至可能是使用VC ++編譯的,默認情況下,在調試模式下編譯時,std :: vector :: operator []會默認檢查邊界。
當我們使用std :: map時,PHP與優化的C ++代碼仍然存在差異,這是因為查找復雜性有所不同(請參閱n0rd的答案),但是使用Hashmap時C ++的速度更快。
根據另一個問題 ,PHP中的關聯數組被實現為哈希表 ,其平均搜索復雜度為O(1),而C ++中的std :: map是具有搜索復雜度為O(log n)的二叉樹。慢點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.