Performance comparison of QDialog on stack and heap
Hi everyone,
I read some articles about memory allocation and free in Qt recently. And I have question about the performance of creating QDialogs on stack (non-pointer) vs on heap (new).
For stack, we just recreate the dialog every time and it should be auto-deleted after we close it, like
Code:
void parentObjectClass::onButtonClick(){
if(dialog.exe()){
// do something
}
}
I think this one will auto delete the dialog instance every time after the dialog is closed. But every time the dialog need to be re-initialized.
For heap, we pre-initialize the object and reuse it every time, like
Code:
// header
Class parentObjectClass{
//....
//...
};
// cpp
void parentObjectClass::initialize(){
}
void parentObjectClass::onButtonClick(){
dialog->setDialog(values);
if(dialog->exe()){
// do something
}
}
This one just reset the dialog contents every time, but if we have a lot of dialogs, we have to initialize all of them when parentObjectClass instance is created, and they will occupy memory until parentObject is deleted.
Am I right? And which way is better for practical using?
Thanks.
Re: Performance comparison of QDialog on stack and heap
Your question is not really about stack-based vs heap-based allocation, but about creating and destroying dialogs everytime they are show and closed vs reusing them. Indeed, your examples can be rewritten to use the opposite allocation strategy:
Code:
void parentObjectClass::onButtonClick(){
if(dialog->exec()){
// do something
}
delete dialog;
}
Code:
// header
Class parentObjectClass{
//....
//...
};
// cpp
parentObjectClass::parentObjectClass() : dialog(this) {
}
void parentObjectClass::onButtonClick(){
dialog.setDialog(values);
if(dialog.exec()){
// do something
}
}
(note that in the second snippet dialog is not necessarily allocated on the stack, it is just allocated in the same memory block as the parentObjectClass.)
Now, about your question. I have no strong opinion on the subject. Does it really have a noticeable impact on the performance of your program? One interesting thing to notice is that by reusing a dialog you preserve its state (position and size) while you need to explicitly store it and re-apply it if you use distinct instances.
Re: Performance comparison of QDialog on stack and heap
Yes I agree. Usually this won't have a big difference. Actually reusing a dialog make the dialog show immediately after the first showing. This should make user feel the difference. (The dialog looks like switching to a hidden window but not popping up.) And plus it keeps the old status as you said, I do think it should be better to recreate the dialog.