Is Calling Functions Slow?

I have a little code here that I am very confused by. All of this is inside a class, which is declared in a header file.

This code is inside a loop, which iterates a ton of times. ind is an int variable declared before the loop begins. RGBQuad buffer_[] is of class scope.

1
2
3
4
5
6
7
//buffer_[ind].rgbRed = 0;
//buffer_[ind].rgbGreen = 0;
//buffer_[ind].rgbBlue = 0;

fillPixel(ind);

++ind;


Here is the code for fillPixel():

1
2
3
4
5
void Renderer::fillPixel (int i) {
        buffer_[i].rgbRed = 0;
        buffer_[i].rgbGreen = 0;
        buffer_[i].rgbBlue = 0;
}


So, clearly, in the loop, if I comment out the call to fillPixel() and uncomment the other three lines, it would do exactly the same thing.

However, if I call fillPixel(), it takes twice as long as just using those 3 lines in the loop. As in, it goes from 38 fps to 17 fps.

This makes me suspect that there is a loss in performance for calling a function. That doesn't sound right to me, and I highly doubt it could be that large of a drop.

The ONLY thing I change in the code is whether I am calling the function, or just using those three lines. Perhaps I am declaring the function in a way that slows it down? I changed the parameter int i to const int i, but that didn't really make a difference.

EDIT: Just to stress this even more, when I switch the commenting, even the compiler says "no relevant changes." I'm not changing anything besides that.

EDIT2: Even if I change the function so it takes no parameters, and take out all the code inside, so it's just an empty function, it is 25 fps, which is still very slow.
Last edited on
Compile in release mode.

Individual operations at the pixel-level should not be put in a function precisely because of this. Calling a function isn't instantaneous, there is some overhead to it, so if the body of the function doesn't take significantly longer than calling the function, you'll see a visible drop in performance as you're seeing.

In release mode, the compiler tries to do some optimizations, like copying the body of short functions into the call location, which removes the overhead but increases the total code size.
Last edited on
Ooooh. Ok. I have no issue with not using the function, I was just curious as to why this happens.

Thanks!
Topic archived. No new replies allowed.