Should I pass a commonly used array using a reference or by value in a game [C++]
This is really simple, I just wanted to get some feedback, I guess.
Long story short I am a super novice programming, and I've recently (about 6 months ago) started doing some game programming, and it's going fine. I can get everything to work and all that, so that's not my question. Instead, this has to do with passing objects.
Pretty much I pass the same object or variable several times through the game loop. So, for cameras, the camera is used to draw ALL the objects. So first the camera is passed to a container object (like for drawing frames of an animation, an 开发者_如何学Canimation object contains the frames), which then passes to the individual object, which then draws. Now, this only passes the camera maybe 3 times max, so it's no worry, yet.
What is more concerning is the similar multiple-passing but with an array of tiles which makes up the map. First the array is passed to the 'Update' function of the player or enemy, which is then passed to individual move and input functions to check for collisions, and in those functions it's passed to the collision detection function. So anyway, pretty much what happens is that the object (in this case, an array of about 100~1000 tiles) gets passed like 4-5 times per game loop. So I was just wondering if I should just use a constant reference instead of passing it over and over again.
Pretty minor overhead issue, and I think I know the answer, but I don't want to change all those functions just to find out I made the application even slower (not that it is since it runs at like 800 fps right now).
If you can modify your programming style to include techniques that make your code perform better, without costing you anything as far as maintenance or readability goes, you should definitely do it.
Beyond this, optimizations should be limited to instances where you know you need it, because you have actually measured your performance and found it lacking.
1) If your application is already fast enough, don't do anything
2) Passing by reference (using &
or *
) is cheap. Do that.
If you're using primitive arrays, they always get passed by reference.
But beyond that, I second Alex Brown's answer - it's easy and cheap, so do it unless you have a reason not to.
Any answer claiming one is better than the other, or visa-versa, is wrong. The only correct answer to this question is to use a profiler and actually look at what parts of the code are taking the longest. Don't change anything to & or *, or visa-versa, until you've done so.
精彩评论