我想检查不同方法的性能,以检查值是否为数组。我使用了console.time和jsperf并得到了相互矛盾的结果。创建脚本并运行它给jsperf提供了类似的结果。
jsperf link http://jsperf.com/is-it-an-array
我的代码
a={test:'a',foo:'bar'};
b='abcdef';
c=[1,2,3,4,5,6]
d=3.14
length=1e6;
l=length;
console.time(1);
while(l--){
a instanceof Array ?true:false;
b instanceof Array ?true:false;
c instanceof Array ?true:false;
d instanceof Array ?true:false;
}
console.timeEnd(1);
l=length;
console.time(2);
while(l--){
a.pop?true:false;
b.pop?true:false;
c.pop?true:false;
d.pop?true:false;
}
console.timeEnd(2);
l=length;
console.time(3);
while(l--){
Array.isArray(a)?true:false;
Array.isArray(b)?true:false;
Array.isArray(c)?true:false;
Array.isArray(d)?true:false;
}
console.timeEnd(3);
l=length;
console.time(4);
while(l--){
a.constructor == Array?true:false;
b.constructor == Array?true:false;
c.constructor == Array?true:false;
d.constructor == Array?true:false;
}
console.timeEnd(4);
在我的计算机上,使用jsperf,Firefox在这些测试中的表现要比Chrome好得多。到目前为止,最快的解决方案是使用instanceof
,最差的解决方案是.pop
。在isArray
中,.pop
最快,.pop
仍然是最慢的。
但是在控制台中运行这些测试会得到不同的结果1: 153.35ms
2: 166.88ms //.pop
3: 169.94ms
4: 193.73ms
永远不会是最慢的。
火狐
1: 286.000ms
2: 207.000ms //.pop
3: 270.000ms
4: 266.000ms
铬
function getCampaignResults(){
global $wpdb;
$table_name = $wpdb->prefix . "campaigns";
$active_rows = $wpdb->get_results(
"SELECT * FROM {$table_name}"
);
foreach ($active_rows as $active_row){
echo $active_row->the_title;
}
}
使用控制台运行代码的原因是什么?