Col*_*mbo 1 php c++ arrays performance map
我无法理解以下内容,我希望有人可以为我阐明一下:
在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;
Run Code Online (Sandbox Code Playgroud)
这需要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.";
?>
Run Code Online (Sandbox Code Playgroud)
......只需3秒钟.
鉴于PHP是用C语言编写的,有没有人知道PHP如何实现这么快的文本索引查找?
谢谢C.
你的循环不是绝对等效的算法.请注意,在C++版本中
在PHP版本中,您只需在第一个循环中插入并在第二个循环中查找.
PHP被解释 - 通常如果您的代码在PHP中更快,请首先检查代码!;-)