Cost of a virtual function in a tight loop

前端 未结 4 1457
别跟我提以往
别跟我提以往 2021-01-18 20:09

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

4条回答
  •  滥情空心
    2021-01-18 20:41

    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.

    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.

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

    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.

提交回复
热议问题