Optimize SWAP
macro by using move semantics.
#100367
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Move semantics help make code faster by changing ownership rather than copying objects. In the case of
SWAP
, a maximum of 3 copies can be avoided, if the underlying objects have corresponding constructors and assignment operators. The current implementation forces the compiler to copy the object for each assignment:Recently, we starting to introduce
move
semantics into the codebase. In particular, there was #100239 forString
,Vector
andCowData
. Hopefully, sometime in the future, we'll get similarmove
constructors and assignments forVariant
. TheSWAP
macro should be ready to accelerate these semantics.The implementation of
std::swap
on my machine (macOS) looks like this:It could be trivially re-implemented in Godot as such:
However, since both
std::swap
andstd::move
are defined in<utility>
(i.e. the include is needed anyway), I see no reason to reinvent the wheel (except maybe to make itconstexpr
?).