Computation overhead in C# - Using getters/setters vs. modifying arrays directly and casting speeds

Posted by Jeffrey Kern on Stack Overflow See other posts from Stack Overflow or by Jeffrey Kern
Published on 2010-06-10T21:08:53Z Indexed on 2010/06/10 21:13 UTC
Read the original article Hit count: 204

Filed under:
|
|
|
|

I was going to write a long-winded post, but I'll boil it down here:

I'm trying to emulate the graphical old-school style of the NES via XNA. However, my FPS is SLOW, trying to modify 65K pixels per frame. If I just loop through all 65K pixels and set them to some arbitrary color, I get 64FPS. The code I made to look-up what colors should be placed where, I get 1FPS.

I think it is because of my object-orented code.

Right now, I have things divided into about six classes, with getters/setters. I'm guessing that I'm at least calling 360K getters per frame, which I think is a lot of overhead. Each class contains either/and-or 1D or 2D arrays containing custom enumerations, int, Color, or Vector2D, bytes.

What if I combined all of the classes into just one, and accessed the contents of each array directly? The code would look a mess, and ditch the concepts of object-oriented coding, but the speed might be much faster.

I'm also not concerned about access violations, as any attempts to get/set the data in the arrays will done in blocks. E.g., all writing to arrays will take place before any data is accessed from them.


As for casting, I stated that I'm using custom enumerations, int, Color, and Vector2D, bytes. Which data types are fastest to use and access in the .net Framework, XNA, XBox, C#? I think that constant casting might be a cause of slowdown here.

Also, instead of using math to figure out which indexes data should be placed in, I've used precomputed lookup tables so I don't have to use constant multiplication, addition, subtraction, division per frame. :)

© Stack Overflow or respective owner

Related posts about c#

Related posts about casting