duanjia4817 2017-10-15 17:36
浏览 56

最优化的方法来创建关联数组

What is the best (fastest, most readable, etc.) way to create associative array?

Last time I saw that my co-worker, create small assoc array by:

$array['is_enabled'] = false;

In code review i pass my opinion that more readable form is:

$array = [
    'is_enabled' => false
];

But "readable" is subjective thing, so it's not the best argument.

  • 写回答

1条回答 默认 最新

  • drfu80954 2017-10-15 17:38
    关注

    The first approach 3v4l link:

    $subscription['is_enabled'] = false;
    

    You can see in link that's generated 3 operations

    number of ops:  3
    compiled vars:  !0 = $subscription
    line     #* E I O op                           fetch          ext  return  operands
    -------------------------------------------------------------------------------------
       3     0  E >   ASSIGN_DIM                                               !0, 'is_active'
             1        OP_DATA                                                  
             2      > RETURN                                                   1
    

    Avg. memory usage is 25.15 MiB and runs in 0.013s (user time PHP 7.1.x).

    The second approach 3v4l link:

    $subscription = ['is_active' => false];
    

    Now it's only 2 operations. Assign and return.

    number of ops:  2
    compiled vars:  !0 = $subscription
    line     #* E I O op                           fetch          ext  return  operands
    -------------------------------------------------------------------------------------
       3     0  E >   ASSIGN                                                   !0, 
             1      > RETURN                                                   1
    

    Avg. memory usage is 24.40 MiB and runs in 0.010s (user time PHP 7.1.x).

    I'm not sure what operation is op_data that is missing in second approach. But still it's one operation less, and in result we gain almost 0,8MiB less memory usage and ~23% faster execution time.


    So it's looks like $array= ['key' => false];

    It's not only more readable but also quite simpler for parser. With this notation we skip one operation from three, and that's give us additional free memory and time.

    评论

报告相同问题?

悬赏问题

  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制