Free Function Pointer vs. Member Function
Question 2 / 12 • Correct so far: 0 (0 answered)
Free Function
struct Particle {
float x, y;
float vx, vy;
};
void step(Particle* p, float dt) {
constexpr float g = 9.81f;
p->vy += g * dt;
p->x += p->vx * dt;
p->y += p->vy * dt;
}
for (int i = 0; i < STEPS; ++i)
step(&p, DT); Member Function
struct Particle {
float x, y;
float vx, vy;
void step(float dt) {
constexpr float g = 9.81f;
vy += g * dt;
x += vx * dt;
y += vy * dt;
}
};
for (int i = 0; i < STEPS; ++i)
p.step(DT); Shared test data (shared-setup)
constexpr int STEPS = 10000;
constexpr float DT = 0.001f; Which snippet is faster?
Both snippets compile to identical machine code. A non-virtual member
function call like p.step(dt) is syntactic sugar: the compiler implicitly
passes this (a pointer to p) as its first argument, exactly as the free
function does explicitly. With both objects on the stack and no virtual
dispatch or inheritance involved, the optimizer sees the same operations and
produces equivalent assembly.
Benchmark results
| Snippet | CPU time / iteration | Speedup |
|---|---|---|
| Free Function | 7.58 us | 1.0× |
| Member Function | 7.39 us | 1.0× |
Explore the source
Open in Compiler ExplorerQuiz complete. You can return to the question list to restart and compare.