为数组键添加前缀的最快方法? [英] Fastest way to add prefix to array keys?

查看:52
本文介绍了为数组键添加前缀的最快方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为数组键添加字符串前缀的最快方法是什么?

What is the fastest way to add string prefixes to array keys?

输入

$array = array(
 '1' => 'val1',
 '2' => 'val2',
);

需要的输出:

$array = array(
  'prefix1' => 'val1',
  'prefix2' => 'val2',
);

推荐答案

我发现 PHPBench 不是非平凡基准测试的好来源.因此,除非您真的对运行 for(....); 感兴趣,否则它不会正确显示哪种语法会更快.我整理了一个简单的基准测试来证明当您在迭代期间同时使用键和值时,foreach 实际上是最快的.

I've found that PHPBench is not a very good source for non-trivial benchmarks. So unless your actually interested in running for(....); it's not going to correctly show which syntax will be faster. I've put together a simple benchmark to show that foreach is actually the fastest when your use both the key and value during the iteration.

实际强制 PHP 从循环迭代中读取值非常重要,否则它会尽力优化它们.在下面的示例中,我使用 doNothing 函数强制 PHP 每次计算键和值.使用 doNothing 将导致对每个循环应用开销,但每个循环的开销相同,因为调用次数相同.

It's very important to actually force PHP to read the values from a loop iteration, or else it'll do its best to optimize them out. In the example below I use the doNothing function to force PHP to calculate the key and value each time. Using doNothing will cause an overhead to be applied to each loop, but it will be the same for each loop since the number of calls will be the same.

foreach 名列前茅,我并不感到惊讶,因为它是迭代字典的语言结构.

I wasn't really that surprised that foreach came out on top since it's the language construct for iterating a dictionary.

$array = range( 0, 1000000 );

function doNothing( $value, $key ) {;}

$t1_start = microtime(true);
foreach( $array as $key => $value ) {
    doNothing( $value, $key );
}
$t1_end = microtime(true);

$t2_start = microtime(true);
$array_size = count( $array );
for( $key = 0; $key < $array_size; $key++ ) {
    doNothing( $array[$key], $key );
}
$t2_end = microtime(true);

    //suggestion from PHPBench as the "fastest" way to iterate an array
$t3_start = microtime(true);
$key = array_keys($array);
$size = sizeOf($key);
for( $i=0; $i < $size; $i++ ) {
    doNothing( $key[$i], $array[$key[$i]] );
}
$t3_end = microtime(true);

$t4_start = microtime(true);
array_walk( $array, "doNothing" );
$t4_end = microtime(true);

print
    "Test 1 ".($t1_end - $t1_start)."\n". //Test 1 0.342370986938
    "Test 2 ".($t2_end - $t2_start)."\n". //Test 2 0.369848966599
    "Test 3 ".($t3_end - $t3_start)."\n". //Test 3 0.78616809845
    "Test 4 ".($t4_end - $t4_start)."\n"; //Test 4 0.542922019958

我在 64 位 Mac OSX 10.6 上使用 PHP 5.3

I'm using PHP 5.3 on 64-bit Mac OSX 10.6

这篇关于为数组键添加前缀的最快方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆