Electronic – Are virtual-functions called at a high frequency suitable for embedded systems

cmicrocontroller

I have a (reasonably powerful) 32-bit MCU.
Would it be unwise to design my system using OOP principles – mainly virtual methods?

I have a virtual method which would be called around 1000/second.
Could this be a problem?

Best Answer

Just like on X86, this is going to depend too much on the specific code that any one answer will be useful. It is also going to depend a lot on the processor (and the memory architecture that processor uses).

A virtual method call in general is a pointer to a vtable, which has a pointer to a function. If you are looking at something where a memory lookup is a single cycle, then this is maybe three instructions, and three cycles (two mov, and an add). If the memory model is more complicated, like on an X86, where a pull out of cache can have drastic consequences in timing, then you could be looking for more than 1000 cycles.

Virtual methods also include the memory overhead of all those vtables, which, depending on memory size and memory pointer size, could get large.

For 1000 calls a second, for a "beefy" 32bit MCU running at a few MHz, and for not a lot of work being done in all those calls. You are probably fine. But if you are doing 1000 calls a second and each call takes a ms to finish, the virtual method calls aren't going to be something you can afford.

Like everything in performance and programming: profile, profile, profile. (or measure, measure, measure.)