douxie2007 2013-01-02 13:32
浏览 48
已采纳

保留一个对象与重新初始化它

Well I guess this is not a normal how-to-do-this-or-that stackoverflow question, but perhaps someone could enlighten me of a better approach for this question.

I've created an interface that could inherit different "engines" depending on a value and return the same object for all engines. This is a short time flat rentals application that has some integration with other applications in other states, obviously each one has a API, so I have to know how to send and receive each one differently and inside my application to be able to have the same object for all APIs. What I do exactly is I initialize something like this.

$flat = new API(array('engine' => 'some_api')); // the array has some more information inside but it is unimportant for the question

Now I have a list of IDs that each of them is for a different API. Something like

$list = array(1 => 'api_1', 2 => 'api_2'); // and more ...

Now for the question!

When iterating over the $list what would you think is better, Retaining all the possible engines inside the API object and for each ID I already have the "engine" initialized inside the API object (probably better speed/performance as everything is already allocated) or should foreach ID create a new API object with only the right "engine" initialized. (Lesser speed/performance but should be better on the memory management).

The API object has no meaning outside of the scope of the iteration so there is no need to retain it further down the line, but perhaps there would be less garbage collection overhead all in all if I just initiate one object instead of say 2 or 4 for the amount of IDs I have.

Any thoughts?

  • 写回答

1条回答 默认 最新

  • douwei1408 2013-01-02 13:37
    关注

    Creating/releasing objects doesn't take that much memory or time. You shouldn't have to worry about it, unless you have thousands of APIs.

    If there's any external IO involved, like connecting to a server, initializing a database connection, querying meta information or reading a file, then it's more efficient to do that as less as possible and only when you need to, but the number of objects in itself won't impact the performance notably.

    Advice: Structure the code in the way that is most readable and maintainable for you. If you do, it is probably efficient enough. Only start restructuring if you really find a bottleneck.

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

报告相同问题?

悬赏问题

  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答