Free Function vs. Member Function

Question 13 / 51 Correct so far: 0 (0 answered)

Snippet A

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);
Snippet B

Member Function

class Particle {
private:
    float x, y;
    float vx, vy;
public:
    Particle(float x, float y, float vx, float vy)
        : x(x), y(y), vx(vx), vy(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?

Select the correct answer(s)