问题描述
我通常使用 PHP从变量数组建设紧凑型()
功能。另外,我可以手动创建数组。有那些用途的任何优点或缺点?我分享双方在以下段这些声明的例子:
紧凑型用法
< PHP
$名称=约翰;
$姓=李四;
紧凑的('名','姓');
?>
输出:
['名'=>'约翰','姓'=>'李四']
手册数组声明
< PHP
$名称=约翰;
$姓=李四;
$数据=阵列(名= GT; $名字,姓= GT; $姓);
?>
输出:
['名'=>'约翰','姓'=>'李四']
我觉得它更preference的问题。
使用
如果我有一堆局部变量的声明,我正好希望我的数组键被命名为同样的方式,紧凑
是很有帮助的。
我不觉得这是如此经常虽然。通常情况下,我定义的数组,它是更为复杂的:
$阵列= [
'富'=> $ something->富()
'酒吧'=> $吧,
巴兹'=> A_CONSTANT
];
要使用紧凑
在这里你必须定义变量 $ foo的
$酒吧
和 $巴兹
第一,这似乎是愚蠢的。
我喜欢紧凑
,我不觉得这是各地有益的大部分时间。
性能
好吧,我不得不去做到这一点。这里是一个非常基本的非科学的绩效对比:
总之,使用紧凑
是一个量级慢。
然而,你必须使用它100,000(在这个例子中)要重要的一秒钟的一小部分。
在换句话说,使用什么最有意义您code。不要担心了令人难以置信的小的性能差异!
I am usually using compact()
function of php for the building array from the variables. Also, I can create that array manually. Are there any pros or cons of those usages? I am sharing an examples both of those declarations on the following segment:
Compact Usage
<?php
$name = "John";
$surname = "Doe";
compact('name','surname');
?>
Output:
['name'=>'John','surname'=>'Doe']
Manual Array Declaration
<?php
$name = "John";
$surname = "Doe";
$data = array("name"=>$name,"surname"=>$surname);
?>
Output:
['name'=>'John','surname'=>'Doe']
I think it's more a matter of preference.
Uses
If I have a bunch of local variables declared, and I happen to want my array keys to be named the same way, compact
is very helpful.
I don't find that to be the case very often though. Typically I'm defining an array that is more complex:
$array = [
'foo' => $something->foo(),
'bar' => $bar,
'baz' => A_CONSTANT
];
To use compact
here you'd have to define your variables $foo
$bar
and $baz
first, which seems silly.
I like compact
, I just don't find it to be all around helpful most of the time.
Performance
Ok I had to go do it. Here's a very basic non-scientific performance comparison:
In short, using compact
is an order of magnitude slower.
And yet, you have to use it 100,000 (in this example) to matter a tiny fraction of a second.
In other words: use what makes the most sense for your code. Don't worry about the incredibly small performance difference!
这篇关于紧凑型()与上PHP手册数组声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!