Archived

This topic is now archived and is closed to further replies.

Structs vs Classes??

This topic is 5533 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Does anybody have any ideas on the pros and cons of using Classes against Structs partivularly from a performance point of view. Lets say ive got 100 characters and I increment their position within a loop. The Class way:
  
///////////////////////////

//Character Class (CCharacter)

///////////////////////////

POINT charPosition;

POINT GetPosition() {
  return charPosition;
}

void SetPosition(POINT newPosition) {
  charPosition=newPosition;
}


///////////////////////////

// Main program

///////////////////////////


CCharacter aCharacter[100];

for(int characterCount=0;characterCount<100;characterCount++) {
  int newxPos=aCharacter[characterCount].GetPosition().x+1;
  int newyPos=aCharacter[characterCount].GetPosition().y+1;
  aCharacter[characterCount].SetPosition({newxPos,newyPos});
}
  
And the struct way:
  
///////////////////////////

// Main program

///////////////////////////

struct {
  POINT charPosition;
} CHARACTER;


CHARACTER aCharacter[100];

for(int characterCount=0;characterCount<100;characterCount++) {
  int newxPos=aCharacter[characterCount].charPosition.x+1;
  int newyPos=aCharacter[characterCount].charPosition.y+1;
  aCharacter[characterCount].charPosition={newxPos,newyPos};
}
  
Would the struct way be significantly faster? Probably not for 100 characters, but lets say 2000. This is simplified code, the character class would obviously contain much more functionality but im just wanting to know if there is any significant overhead in having the code class based. (Or is a struct basically a class anyway in which case I guess there would be no difference).

Share this post


Link to post
Share on other sites
Um...I don't know much about OO...but given your example...the struct way should be faster

I'm baseing this on the fact that in the class basied example you are changeing the position by useing a function...which would require some extra work with the stack...pushing/poping variables, jump calls, etc...plus the extra function calls to return the variable values in the class.

In the struct you are changeing them directly (no function calls).

but then I don't know how the compiler deals with classes and such....

Hmm...now that I think about how does the compiler deal with the data in a class?

I meen in the struct you have the bennefit of ajacent memory storage because of the array used...so there is a potential speed increase from useing the cache...and because you are increaseing both X and Y by 1 you could make the routine even faster by dropping the need to temporarily store a integer X and Y value and just use the CPU registers instead...


[edited by - MSW on October 21, 2002 12:37:56 AM]

Share this post


Link to post
Share on other sites
quote:
Original post by RedGenie
Does anybody have any ideas on the pros and cons of using Classes against Structs partivularly from a performance point of view.

Structs are classes in C++, which means that your "struct" example isn''t the C++ use of them, which negates the comparison.

Share this post


Link to post
Share on other sites
You''re thinking too much. It''s not Structs vs Classes. It''s Structs and Classes. Use them where it is appropriate (although c only lets you use structs and c++ rhetoric says ONLY use classes for EVERYTHING). When something needs to be protected or inheritance, polymorphism, etc.., use classes, when something needs quick excessabilty with minimal protection use structs.

"Love all, trust a few. Do wrong to none." - Shakespeare

Dirge - Aurelio Reis
www.CodeFortress.com
Current Causes:
Nissan sues Nissan

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
For that specific purpose it is often faster, unless the class''s function is inlined. In an optimised build you are better off profiling it or looking at the assembly output manually if you are picky on performance. I doubt its anything but marginal however.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
For that specific purpose the struct is often faster, unless the class''s function is inlined. In an optimised build you are better off profiling it or looking at the assembly output manually if you are picky on performance. I doubt its anything but marginal however.

Share this post


Link to post
Share on other sites

.. from what i've heard functions in a class are automatically inline functions. so the class might run at the same speed (or a little bit faster) as the struct version.

of course i'm a beginner in OO so i'm guessing.
if i'm wrong, they roast (read: flame) me and correct me anyway.

[edited by MKV]



[edited by - MadKeithV on October 22, 2002 7:27:30 AM]

Share this post


Link to post
Share on other sites
quote:
Original post by Dirge
c++ rhetoric says ONLY use classes for EVERYTHING



In C++, a struct IS a class, with the ONLY standard difference being that the default access specifier in a struct is public, and in a class private.

It has already been said in this thread too, but apparently, reading is not a requirement for responding anymore.

MSW - there is a potential function call involved with using a function-based modification, yes, but for most short functions the compiler will try to inline it, negating the difference. The keyword 'inline' can be added to demonstrate that you know the function-call overhead might prove a bother, but in the end it's still up to the compiler to decide if it can or cannot inline the function. Usually it does, for short functions like in the example.

[edit: for functions that have their bodies within the class specification (i.e. usually in the header file i.s.o. the CPP file), inline is implied, meaning the compiler will try hard to remove any function-call overhead and some temporary-object construction overhead]



[edited by - MadKeithV on October 22, 2002 5:34:28 AM]

[edited by - MadKeithV on October 22, 2002 8:29:42 AM]

Share this post


Link to post
Share on other sites
quote:

MSW - there is a potential function call involved with using a function-based modification, yes, but for most short functions the compiler will try to inline it, negating the difference. The keyword ''inline'' can be added to demonstrate that you know the function-call overhead might prove a bother, but in the end it''s still up to the compiler to decide if it can or cannot inline the function. Usually it does, for short functions like in the example.

[edit: for functions that have their bodies within the class specification (i.e. usually in the header file i.s.o. the CPP file), inline is implied, meaning the compiler will try hard to remove any function-call overhead and some temporary-object construction overhead]



Now that is what bothers me...this dependancey on the compiler to do such things...when there is a chance (no matter how small) that it won''t...I''m a bit of a control freak when it comes to programming, and don''t feel comfortable with the compiler "second guessing" my code...but hey, thats me...

Share this post


Link to post
Share on other sites
quote:
Original post by MSW
Now that is what bothers me...this dependancey on the compiler to do such things...when there is a chance (no matter how small) that it won''t...I''m a bit of a control freak when it comes to programming, and don''t feel comfortable with the compiler "second guessing" my code...but hey, thats me...



You are also relying on your compiler to produce good hex code. Do you go through the hex-code that your compiler ends up generating (I know people that do, to make sure it acts as they expect!). Inlining is not a black art. There are simply some things that cannot be efficiently or effectively inlined, such as recursive functions, and very large functions (they would give a considerable code bloat).

You think you''re a control freak, but there are thousands of things that you are implicitly relying on anyway. The best thing to do is to either trust the compiler, or really know your stuff and check exactly what the compiler is doing for certain cases, so that you can be sure.

For 95% of programmers out there, the compiler will do a better job at optimising than the programmer could hope to achieve, and in much less time. There are of course always things you NEED to know about the language and about how things get compiled to produce efficient code, but it''s no different from assembly language - branch prediction, MMX, SSE, cache optimisation, etc. are all things you''ll need to consider to produce similar code to your compiler!

So, don''t worry about it too much. If it really bothers you, and you REALLY need the performance, dig deeper.

Share this post


Link to post
Share on other sites
quote:
Original post by MSW
Now that is what bothers me...this dependancey on the compiler to do such things...

Computers exist to automate mindlessly dull repetitive tasks. That includes inferring rules-based decisions from large amounts of data, which is precisely what a compiler can do for you in certain circumstances. Every time you use a compiler, you are relying on it to do such things for you.
quote:

when there is a chance (no matter how small) that it won''t...

Yes, there is a chance the compiler is buggy, but it is usually fairly simple to verify the operation and to extrapolate your findings to the general case.
quote:

I''m a bit of a control freak when it comes to programming, and don''t feel comfortable with the compiler "second guessing" my code...but hey, thats me...

You''re simply being superstitious. You already rely on your compiler to make other decisions, why is this one so special?

Share this post


Link to post
Share on other sites
While I realise that some topics come up over and over, and get tired sometimes, leave moderating to the moderators. Please leave off-topic posting and flaming to the lounge. If you have no desire to have the argument again, there are two options:
1. Point to the original argument thread (which I know is hard, with the search function disabled).
2. Just don't reply at all, letting other people handle the question.


(Better, Sabreman? I apologise for anything that might have been construed as a personal attack, and assure you it was not intentional.)

[edited by - MadKeithV on October 22, 2002 8:16:24 AM]

Share this post


Link to post
Share on other sites
Well thanks for the responses guys.

I think I managed to pick out that there is no significant performance difference, if any, even though opinions seem to be divided.

I''ll probably end up doing some testing at some point to make sure.


But I tell you what I wasnt expecting the level of response it received, these forums are anything but dull! Thanks for the entertainment as well

Share this post


Link to post
Share on other sites
quote:

Do you go through the hex-code that your compiler ends up generating



LOL...I have done that

quote:

So, don''t worry about it too much. If it really bothers you, and you REALLY need the performance, dig deeper.



It''s pretty clear for this particular example that the class structure might not be the right way to go...at least given maybe a .00001% chance the compiler may miss the oppertunity to inline the function calls.

It''s also pretty clear that this example isn''t the best display of the power of OO programing, right?

Lets say you were working on a Pac Man clone...you have a maze filled with dots...the ghosts...pac man himself...the "power pills"...and the little "cherry" piece that roams the maze...

Now you could make each of the dots a object, as well as everything else...have them inherit from other base objects like 2Dpoint and so forth and so on...

but is that really the way OO is ment to be used?...sorry, this is tieing into another thread...maybe I do understand OO, but am confused on where it would prove most usefull...I meen you take this Pac Man clone...which I think wouldn''t bennefit a whole lot by OO abstraction (seems like overkill), but others might (even insist on it)...which makes the whole matter confuseing to me.


Share this post


Link to post
Share on other sites
Ok, no harm done I got my question answered, so cool.

Let me take it a step further because it was really a Class vs Struct performance question.

I did a very simple example so the post wasn''t huge.

Take this example for instance, would there be any performance difference?


The class way:

  
////////////////////////////////

// Character Class (CCharacter)

////////////////////////////////


POINT charPosition;
POINT path[50];

void FindPath() {
// function contains some intensive pathfinding code

}

////////////////////////////////

// Implementation

////////////////////////////////


CCharacter aCharacter[100];

for(int charCount=0;charCount<100;charCount++) {
aCharacter[charCount].FindPath();
}



And the struct way:

  
////////////////////////////////

// Implementation

////////////////////////////////


struct {
POINT charPosition;
} CHARACTER;

// PROTOTYPE

void FindPath(CHARACTER theCharacter);

CHARACTER aCharacter[100];
POINT path[50];

for(int charCount=0;charCount<100;charCount++) {
FindPath(aCharacter[charCount]);
}

void FindPath(CHARACTER theCharacter) {
// function contains some intensive pathfinding code

}



I realise there are some issues in that I could use a linked list or dynamic array for the path but this is simplified for the example.

Share this post


Link to post
Share on other sites
maybe not Pac Man.
but imagine if you were dong an RTS game or an action 2D game.
it is IMHO to use OO for that task.
well first you are gonna have characters.
and those characters will do something.
so it would be better to use a class character than let''s say a C struct character.
from there you can inherit from the base class and make farmers, soldiers, potential road kill victims, or whatever!

for (please pray i don''t get flamed for use of class and being a beginner) example:

class character
{
public:
void attack (weapon, character);
int currentHealth (int health);
void selectWeapon (...);
private:
int health;
int weapon;
string weaponname;
int xposition, yposition;
}

in this makeshift class declaration (please SabreMan don''t flame me) what the character is "composed of" and what he can do with and to his composition is nicely put together here.
all characters will be able to use base class and can add necessary things if needed.

i hope this made some sense and helped even a little.

Share this post


Link to post
Share on other sites
quote:
Original post by RedGenie
Take this example for instance, would there be any performance difference?



If the pathfinding code is really so heavy, then the overhead of potentially non-inlined functions will be minimal. You might lose a very small amount of performance, but it will be negligible.


Share this post


Link to post
Share on other sites
quote:

quote:
--------------------------------------------------------------------------------
Original post by Dirge
c++ rhetoric says ONLY use classes for EVERYTHING

--------------------------------------------------------------------------------



Nitwit rhetoric keeps missing the point that in C++, a struct IS a class, with the ONLY standard difference being that the default access specifier in a struct is public, and in a class private.

It has already been said in this thread too, but apparently, reading is not a requirement for responding anymore.


uhhh... MadKeith shouldn't you edit that since it falls within the bounds of what you call "flaming and not answering the question"?

edit: correction

[edited by - Alpha_ProgDes on October 22, 2002 8:27:37 AM]

Share this post


Link to post
Share on other sites
Must be cool to be a moderator; You can alter the past, and not just your own past .. I just refreshed and half of the posts near the end disappeared (this will too?)

Share this post


Link to post
Share on other sites
quote:
Original post by civguy
Must be cool to be a moderator; You can alter the past, and not just your own past .. I just refreshed and half of the posts near the end disappeared (this will too?)


The whole point is to clean up the thread. All the people involved have read the posts involved, and there's no need to keep dragging in new people in one big flame war for a few posts (some by me) that were over the redline.



[edited by - MadKeithV on October 22, 2002 8:33:13 AM]

Share this post


Link to post
Share on other sites