I want to know about emit
. Does it duplicate data?
If I have to pass a 1MB byte array through it, how many copies of that byte array will exist in memory?
That depends on how your signals are connected to slots.
If you use the default connection, Qt::DirectConnection
, and the two QObject
s are in the same thread, then the parameters are treated as if you were calling function in the usual way according to how you defined the parameters(pass-by-reference or pass-by-value).
If you connect using Qt::QueuedConnection
or you are connected between threads, then the parameter arguments are copied and handed over to a special QEvent
and added to the receiving thread's event queue. This will then be processed by the receiving thread when it gets the chance.
It depends on how the connections are made, and how you pass the parameters.
Pass by value (i.e. signals: void foo(Bar);
)
Bar
from caller to callee).moc
is called (one copy, same as the one above), "packages" the parameter and calls QMetaObject::activate
which ends up calling your class's qt_static_metacall
, which invokes the slot (as a normal function call), incurring a second copy.qt_static_metacall
invocation of the slot.Pass by const reference (i.e. signals: void foo(Bar const&);
)
Pass by (non-const) reference (i.e. signals: void foo(Bar&);
)
The copy into an event is mentioned in the docs:
With queued connections, the parameters must be of types that are known to Qt's meta-object system, because Qt needs to copy the arguments to store them in an event behind the scenes.
Now the real question is: does this matter?
If you're using a Qt container class that uses implicit sharing, it won't really matter in usual cases - the payload won't be copied unless required. So the copies shouldn't have a significant impact on overall performance in general.
If you're not using implicit sharing, then passing massive objects by value probably isn't the right choice in the first place, but a slot invocation would be more expensive than a plain function call. Direct-connected slots and pass-by-const-ref will behave the same as normal function calls, but queued slots will be more expensive.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With