一个虚函数的成本在一个紧的循环 [英] Cost of a virtual function in a tight loop

查看:147
本文介绍了一个虚函数的成本在一个紧的循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个情况下,我有游戏对象有一个虚拟函数Update()。有很多游戏对象(目前有点超过7000)和循环调用更新所有的(除其他外)。我的同事建议,我们应该删除虚函数。你可以想象,这将需要很多重构。

I am in a situation where I have game objects that have a virtual function Update(). There are a lot of game objects (currently a little over 7000) and the loop calls update for all of them (amongst other things). My colleague suggested that we should remove the virtual function altogether. As you can imagine, this will take a lot of refactoring.

我看过这个答案,但在我的情况下,profiling意味着我必须改变很多代码。所以在我甚至想到开始之前,我想我会问这里是否重构是值得的在这种情况下的意见。

I have seen this answer but in my case, profiling means I have to change a lot of code. So before I even think of starting I thought I'd ask here for opinion on whether refactoring is worth it in this case.

请注意,我已经剖析了循环的其他部分,并一直在尝试优化最长的部分。我怀疑虚拟函数调用在这种情况下是我不应该担心的,但我不能确定,直到我的配置文件,我不能配置,直到我改变代码(这是很多)。另请注意,一些更新函数非常小,而其他更大更复杂。

Note that I have profiled other parts of the loop and have been trying to optimize the parts that are taking the longest. I suspect that the virtual function calls in this case is something I should not worry about, but I cannot be sure until I profile and I cannot profile until I change the code (which is a lot). Also note that some update functions are very small while others are larger more complex.

EDIT :有多个答案,

推荐答案

如果有任何人在未来绊倒这个问题,请查看所有的答案,你不能配置文件,看看汇编代码来了解查找真正是多么昂贵。它可能是一个简单的间接跳转,几乎不花费任何成本。

If you can't profile, have a look at the assembler code to get an idea how expensive the lookup really is. It might be a simple indirect jump which costs almost nothing.

如果你需要重构,这里是一个建议:创建大量的UpdateXxx类,知道如何调用新的非虚拟 update()方法。收集这些在数组,然后调用 update()在他们。

If you need to refactor, here is a suggestion: Create lots of "UpdateXxx" classes which know how to call the new non-virtual update() method. Collect those in an array and then call update() on them.

但我的猜测是,特别是对于只有7K对象的情况来说更是如此。

But my guess is that you won't save much, especially not with only 7K objects.

注意:如果你不能使用分析器(让我想知道为什么不) update()和日志调用花费的时间比例如100ms。时间并不昂贵,它允许您快速找出哪些电话是最昂贵的。

Note on profiling: If you can't use a profiler (makes me wonder why not), time the calls to update() and log calls which take longer than, say, 100ms. The timing isn't expensive and it allows you to quickly figure out which calls are most expensive.

这篇关于一个虚函数的成本在一个紧的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆