Move QMenu allocation from heap to stack
ClosedPublic

Authored by dkurz on Aug 3 2017, 7:05 PM.

Details

Reviewers
dvratil
Group Reviewers
KDE PIM: KMail

Diff Detail

Repository
R206 KMail
Lint
Lint Skipped
Unit
Unit Tests Skipped
dkurz created this revision.Aug 3 2017, 7:05 PM
Restricted Application added a subscriber: KDE PIM. ยท View Herald TranscriptAug 3 2017, 7:05 PM

Why ? What is the improvement ?

dkurz added a comment.Aug 4 2017, 10:03 AM

We save one heap allocation. Stack allocations are always cheaper. Also, we reduce the risk of a memory leak, when for some reason the "delete menu" isn't reached.

As I see there is a delete menu without other branch so for me it's not really useful.
Regards

dkurz added a comment.Aug 4 2017, 11:28 AM

But we still save an inefficient heap allocation. That's already useful in itself. And there's really no point in creating this QMenu on the heap here.

From my point of view, I think it's a harmless change that makes the code better readable, safer and faster (even though the performance gain here has a negligible impact). I don't see a reason to not merge it.

dkurz added a comment.Aug 11 2017, 7:57 AM

So now we have readability, memory safety and performance on the plus side. To further back my performance claim, [1] investigates the difference between stack and heap allocation. Short answer: depends on the platform, but stack allocation can easily be faster by two orders of magnitude for a simple single-threaded program. KMail is multithreaded, so we can expect bigger differences: Heap allocation causes threads to synchronize on most platforms, because the heap is a shared resource (see e.g. [2]). The kind of allocation also hints at the expected lifetime of an object (in C++; in Qt, this is somewhat questionable).

[1] https://stackoverflow.com/questions/161053/which-is-faster-stack-allocation-or-heap-allocation
[2] https://stackoverflow.com/questions/1665419/do-threads-have-a-distinct-heap

stack is always a good default

Note however that the performance claims don't apply here because menu.exec() is a "time bottleneck", if you call this function 100000 times you can't say it ran noticeably faster, since all the time was spent in exec().

anyway, +1, it's good to have code without new and delete

dvratil accepted this revision.Aug 14 2017, 7:58 AM
This revision is now accepted and ready to land.Aug 14 2017, 7:58 AM
dkurz closed this revision.Aug 21 2017, 6:03 PM