doubi3996 2017-03-10 17:27
浏览 38
已采纳

Symfony2:查找函数中的对象vs将对象传递给函数

I have a function in Symfony2 that modifies an object. The function can receive the object in one of two ways. First, the object can be passed to the function like this:

public function myFunction(Object $myObject)
    {
        // Do something with $myObject
    }

Alternately, an object id (or any other attribute) can be passed to the function and used to find the object within the function, like this:

public function myFunction($id)
    {
        $myObject = $this->entityManager->getRepository('AppBundle\Entity\Object')->find($id);
        // Do something with $myObject
    }

Functionally, these two methods are equivalent. My question is, how do these two methods differ in their effect on the application's performance? I know the number of database queries should be minimized for optimized performance. So, how does the performance cost of an additional find() query compare with the performance cost of passing an object to a function?

  • 写回答

1条回答 默认 最新

  • dongxing2015 2017-03-18 19:16
    关注

    Passing the object to the function will always be more performant. Since PHP5 objects are passed by object identifier, very similar in concept to pass by reference.

    That said, retrieving a single record of raw data from the database is relatively fast. In my experience, hydration (transforming the relational data retrieved from the database into it's mapped business object) is where you find bottlenecks. Marco Pivetta, lead developer of Doctrine, has written an excellent post about this.

    Generally speaking, under normal circumstances you will probably notice no difference in performance between passing an object and hydrating a single object. Hydrating in loops, however, is where you run into trouble. The more complex the object, and the more data you hydrate, the worse the performance.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥15 pyqt信号槽连接写法
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。