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 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题