Lambda vs Bind
条评论Source Code
1 | // https://godbolt.org/z/9xnnqPTKo |
Assembly Analysis of InitBind()
The assembly code for InitBind()
reveals why it’s generally considered less efficient than the lambda approaches. Here’s what’s happening:
Stack Setup and Function Preparation
1 | push rbx ; Save rbx register for later use |
Creating the Bound Function Object
1 | lea rbx, [rsp + 56] ; Store destination address in rbx |
Converting to std::function and Registering
1 | lea rdi, [rsp + 24] ; Set destination for std::function |
Cleanup
1 | lea rdi, [rsp + 24] ; Load address of std::function |
Performance Implications
-
Multiple Function Calls: The code makes several function calls:
- To
std::bind_front
- To
std::function
constructor - To the
Register
function - To destructors
- To
-
Object Construction: It constructs intermediate objects:
- A
_Bind_front
object - A
std::function
object
- A
-
Memory Operations: There are many memory operations:
- Stack allocations (80 bytes)
- Multiple pointer manipulations
- Storing/loading function pointers
-
Indirection: The use of function pointers adds indirection
Lambda approaches avoid most of this overhead by creating simpler, more direct function objects that the compiler can often inline more effectively.
Comparing Assembly: InitLambda()
vs InitBind()
Looking at the assembly for both functions, there are clear differences that explain the performance characteristics:
InitLambda() Assembly Overview
1 | push rbx ; Save rbx register |
Key Differences
-
Stack Usage:
InitLambda()
: Uses only 48 bytes on the stackInitBind()
: Uses 80 bytes on the stack
-
Function Calls:
InitLambda()
: Has only 3 function callsInitBind()
: Has 4 function calls including the extrastd::bind_front
call
-
Complexity:
InitLambda()
: The assembly is simpler with fewer instructionsInitBind()
: More instructions and memory operations
-
Object Construction:
InitLambda()
: Directly constructs astd::function
from the lambdaInitBind()
: Creates an intermediate_Bind_front
object first, then converts it to astd::function
Performance Implications
-
Memory Efficiency:
InitLambda()
uses less stack space and has fewer memory operations -
Call Overhead:
InitLambda()
has fewer function calls, reducing call overhead -
Inlining Potential: Lambda code is more likely to be inlined by the compiler since it’s direct
-
Simplicity:
InitLambda()
generates simpler code that’s easier for the processor to execute efficiently
The comparison confirms that lambda-based approaches generally produce more efficient code than std::bind_front
, as they avoid the additional indirection and object creation overhead.
本文标题:Lambda vs Bind
文章作者:Henry Wu
发布时间:2025-04-15
最后更新:2025-08-20
原始链接:https://henrywu.netlify.app/2025/04/15/Lambda-vs-Bind/
版权声明:转载请注明出处。CC BY-NC-SA 4.0