Dynamic or Static polymorphism - what is better?

As I understand, dynamic polymorphism can use more SRAM, and static polymorphism may use more program space. Is this statement correct?

Should I prefer to use static polymorphism If I want to use less memory for vtbl? does it really beneficial.
Here is a simple example with two approaches

#include <iostream>

struct Message {
    int value;
};

class MessageReceiver {
public:
    virtual Message receive()= 0;
};

class ConcreteMessageReceiver : public MessageReceiver {
public:
    Message receive() override {
        return {};
    }
};


class ConcreteTemplateMessageReceiver {
public:
    Message receive() {
        return {};
    }
};


class ClientA {
    MessageReceiver *messageReceiver;
public:
    ClientA(MessageReceiver *messageReceiver) : messageReceiver(messageReceiver) {}

    void doSomething() {
        const Message &message = messageReceiver->receive();
    }
};

template<typename R>
class ClientB {
    R receiver;
public:
    ClientB(R receiver) : receiver(receiver) {}
    void doSomething() {
        Message message = receiver.receive();
    }
};


int main() {
    ConcreteMessageReceiver concreteMessageReceiver;
    ClientA clientA{&concreteMessageReceiver};
    clientA.doSomething();

    ConcreteTemplateMessageReceiver concreteTemplateMessageReceiver;
    ClientB<ConcreteTemplateMessageReceiver> clientB{concreteTemplateMessageReceiver};
    clientB.doSomething();
    return 0;
}

Will code for ClientB use less SRAM?

Neither has side effects so the optimizer removes the entire lot.

The point is ... Get it working. Then optimize.

In general, microcontrollers have more leeway in program space than RAM.

If you're going to ask here, please put your sample program in a form that compiles on some variety of arduino-related board. Which board you use can make a significant difference; for example pointers to functions are comparatively expensive on an AVR, because there's only one register (pair) that can be used by the ICALL/IJMP instructions.

My project is pretty big and I won't be able to put it here.

I use Listener pattern , where multiple listeners need to react differently on a particular event(e.g. button is pressed and I need to display a message and run motor). Here I use runtime polymorphism as I am not sure if it is possible to do it with templates. Is it?

For different devices I also use runtime polymorphism but I can migrate to templates if it is beneficial.

afedorov:
I use Listener pattern...

Observer pattern?

A VMT will consume more memory because it needs to keep track of an array of pointers to all virtual methods. Template classes (static polymorbidcats) will require the compiler to implement the codebase for an entire class for each required data type and this will of course increase the size of the binary code.

Now, what is the better sollution: That depends! :wink: