dongzhen4180 2017-12-14 04:57
浏览 24

PHP / OOP使用Classname vs直接使用NameSpace \ Classname

Please consider the codes below.

Code1:

<?php
use App\User;

class SomeController {

    public function getUsers()
    {
        return User::all(); 
    }
}

Code2:

<?php
class SomeController {

   public function getUsers()
   {
      return \App\User::all();
   }
}

I got confused whether these two have that much impact to its performance. I know that the first way of coding seems really the better/nicer way but what if I just want to use the User class just once on my Controller? Which is the better choice for single-used class?

  • 写回答

1条回答 默认 最新

  • drxm72811 2018-01-05 17:43
    关注

    Personally, if I know I am going to use a class reference exactly once, I use the full reference in-situ and forget the use. The benefit to the use is that if a class is referenced many times then it is easier to rename the class name or the namespace if use is used (since there are fewer refs to repair).

    I would expect that there are no performance improvements one way or the other, and if there were, it would be such a trivial improvement that a better server would be an easier way to realise those speed benefits. I tend to advocate against trying to squeeze performance improvements this way, as it encourages reducing readability over benefits that are too small to be noticeable.

    This sort of consideration may also be a premature optimisation, i.e. an optimisation that wastes engineering effort on something that is not actually a problem (either now or in the future). There is a good discussion on that here.

    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大