Using virtual functions instead of IF statements is faster?

I remember reading somewhere on the Internet that in extreme situations with low latency it is better to use virtual functions as a replacement for IF statements.

It's true? Do they mostly say that dynamic polymorphism is better for high-speed situations?

Does any user have any other C ++ low latency "quirks" that they could use?

+6
source share
1 answer

I highly doubt that a single if / else statement will be slower than using a virtual function: a virtual function usually uses a pipe rack and limits optimization options. The if statement can stop the pipeline, but if it is often executed, prediction can go the right way. However, if your alternative is between a cascade of several if / else statements and only one virtual function call than the last one, it might be faster. In addition, if the general code executed using virtual functions with respect to branches differs from different functions, it becomes much smaller, this can lead to small misses in the instruction cache. That is, it depends on the situation. The best way is to measure. Note that measuring a fake code that just tries to investigate the difference between the two approaches, but does not actually do any processing, leads to misleading results. However, when you need to create code with a very low latency, you can usually spend more time thinking of it, that is, experimenting with several different approaches can be viable.

Although my colleagues are generally dissatisfied with my approaches to templates to avoid branching at runtime, the code in which I end up often compiles very slowly, but it runs very quickly. Of course, this depends on the functions or branches that are used at compile time. In areas that I used, for example, for processing messages, one dynamic solution is often enough, for example. one for each message (i.e., one call to a virtual function), followed by processing that does not include any dynamic types (this is still conditional, for example, for the number of values ​​in a table).

+7
source

Source: https://habr.com/ru/post/906001/


All Articles