直接贴代码:
<?php
ini_set('memory_limit','2024M');
$totalArr = [];
for($i=1;$i<10000000;$i++){
$totalArr[] = rand(1,1000000);
}
$newTree = [];
$time1 = floatval(time())+floatval(microtime());
foreach ($totalArr as $v){
$newTree = buildTree($newTree,$v);
}
$time2 = floatval(time())+floatval(microtime());
$result = findTree($newTree,9990);
$time3 = floatval(time())+floatval(microtime());
echo 'buildSpendTime: '.($time2-$time1);
echo 'FindSpendTime: '.($time3-$time2)*100;
print_r($result);
exit;
/**
* @param $tree 旧的树的数据
* @param $item 数据
*/
function buildTree($tree,$item){
if($tree==[]){//第一次构建
$tree['value'][] = $item;
}else{
if($item == $tree['value'][0]){
$tree['value'][] = $item;
}else if($item>$tree['value'][0]){//大于等于 放右边
if(!isset($tree['right'])) {
$tree['right'] = ['value'=>[$item]];
}else{
$tree['right'] = buildTree($tree['right'],$item);
}
}else{
if(!isset($tree['left'])) {
$tree['left'] = ['value'=>[$item]];
}else{
$tree['left'] = buildTree($tree['left'],$item);
}
}
}
return $tree;
}
/**
* 查找树
* @param $tree
* @param $value
*/
function findTree($tree,$value){
if(!$tree){
return false;
}else{
if($tree['value'][0] == $value){
return $tree['value'];
}else if($value > $tree['value'][0]){
if(isset($tree['right'])){
return findTree($tree['right'],$value);
}else{
return [];
}
}else{//left
if(isset($tree['left'])){
return findTree($tree['left'],$value);
}else{
return [];
}
}
}
}
运行结果
buildSpendTime: 751.73062205315FindSpendTime: 0.0063896179199219Array
(
? ? [0] => 9990
? ? [1] => 9990
? ? [2] => 9990
? ? [3] => 9990
? ? [4] => 9990
? ? [5] => 9990
? ? [6] => 9990
? ? [7] => 9990
? ? [8] => 9990
? ? [9] => 9990
? ? [10] => 9990
? ? [11] => 9990
)
Process finished with exit code 0
1000w 数据,生成+ 构建树 耗时间 751.73062205315
查找数据? ?0.0063896179199219
当然这个不是 B+树 只是普通二叉树
不过也可以看出 mysql 创建索引确实很耗时,有索引的情况下查询真的很快。
|