Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: using a lot of structs can make a program slow?

I am coding a breakout clone. I had one version in which I only had one level deep of structures. This version runs at 70 fps.

For more clarity in the code I decided the code should have more abstractions and created more structs. Most of the times I have two two three level deep of structures. This version runs at 30 fps.

Since there are some other differences besides the structures, I ask you: Does using a lot of structs in C can slow down the code significantly?

For example on the second version, I am using:

struct Breakout
{
   Ball ball;
   Paddle paddle;
   Level* levels;
}

struct Level
{
   Bricks* bricks;
}

So, I am using lots of times breakout.levels[level_in_play].bricks[i].visible for example. Will this be a possible cause?

Thanks.

like image 968
nunos Avatar asked Nov 30 '22 10:11

nunos


1 Answers

Doing a lot of pointer dereferences can be a performance hit. When you split a big struct up into smaller structs, two things happen:

  1. Accessing a member of a sub-struct requires an additional pointer dereference and memory fetch, which is slightly slower, and
  2. You can reduce the locality of reference, which causes more cache misses and page faults and can drastically reduce performance.

The locality of reference one is probably what is biting you here. If possible, try to allocate related structs in the same malloc block, which increases the likelihood that they will be cached together.

like image 165
Daniel Pryden Avatar answered Dec 15 '22 04:12

Daniel Pryden