Struct faster than class?

W

wackyphill

If you have a function that basically creates an object/struct that
holds data only in a function and wish to return the object/struct from
the function which is faster a class object or struct?

I would have thought class object since it can be passed back as an
object reference instead of copying an entire struct, but I've read
things that make me question if structs are in fact faster.

What's the truth?
 
J

Jon Skeet [C# MVP]

If you have a function that basically creates an object/struct that
holds data only in a function and wish to return the object/struct from
the function which is faster a class object or struct?

I would have thought class object since it can be passed back as an
object reference instead of copying an entire struct, but I've read
things that make me question if structs are in fact faster.

What's the truth?

The return would be faster with a class. However, you'd need to create
the instance on the heap to start with, which would be more expensive
than creating the struct on the stack.

However, you should really ask whether you want value semantics or
reference semantics. The "default" answer should be to create a class.
It's very rarely a good idea to create a struct. There are all kinds of
surprising (if you're not careful) bits of behaviour otherwise -
particularly for mutable structs.
 
W

wackyphill

Well, for an e-commerce site where each product could be a struct or
class it seems reasonable to not want to incur overhead if not
necessary.
 
J

Jon Skeet [C# MVP]

Well, for an e-commerce site where each product could be a struct or
class it seems reasonable to not want to incur overhead if not
necessary.

Not until you've actually got a performance problem. Micro-optimisation
kills readability and elegant design if you let it. Work out the
simplest way to do it, paying attention to *macro*-optimisation (in
terms of transactions, web service chattiness etc), and then see
whether that performs well enough. If it doesn't, find the bottleneck
and optimise *that*.
 
J

Jon Skeet [C# MVP]

Jon Skeet said:
Not until you've actually got a performance problem. Micro-optimisation
kills readability and elegant design if you let it. Work out the
simplest way to do it, paying attention to *macro*-optimisation (in
terms of transactions, web service chattiness etc), and then see
whether that performs well enough. If it doesn't, find the bottleneck
and optimise *that*.

Sorry, I should have included a link to Ian Griffith's excellent
mailing list post (now on his blog):

http://www.interact-sw.co.uk/iangblog/2005/11/09/profiling
 
W

wackyphill

Ya know, I'd rather you not answer the question than tell me something
completely other than what I was asking about.

1st off a struct is not in the least complex.
2nd I asked specifically about speed. Not about design. It's a speed
question, I don't care what you think is a good use of design time.

It was a specific speed question, between a class object and a struct,
nothing else.
I don't get why people want to try and tell other people that there
questions aren't the right ones.
 
J

Jon Skeet [C# MVP]

Ya know, I'd rather you not answer the question than tell me something
completely other than what I was asking about.

Sorry, I'll give you a full refund.
1st off a struct is not in the least complex.

That statement may well come back to bite you, especially if you make
your structs mutable. How well do you know the rules about when a
struct's variable is definitely initialised? How about what the effects
of unboxing are? Why is:

object o = GetSomethingFromSomewhere();
((SomeClass)o).Value = 5;

valid but

object o = GetSomethingFromSomewhere();
((SomeStruct)o).Value = 5;

isn't?
2nd I asked specifically about speed. Not about design. It's a speed
question, I don't care what you think is a good use of design time.

That's an unfortunate attitude, but never mind.
It was a specific speed question, between a class object and a struct,
nothing else.
I don't get why people want to try and tell other people that there
questions aren't the right ones.

Because it's proven to be useful so many times in the past.

For instance, someone asked a while ago what the equivalent of some
Delphi code was in C#. What they really *wanted* was some C# code which
accomplished the same result - and the best solution to that was
actually to use regular expressions, rather than to transcribe the
Delphi into C#. Do you really think the best answer would have been to
give the transcription?

Why would you *not* want to know about other things which should affect
your decision, beyond the thing you happen to have thought of to start
with? Do you trust yourself to think of everything and have more
experience of the issues than everyone on the newsgroup? I know I don't
when I ask a question.
 
S

sdbillsfan

Jon,
Based solely on your postings to this and other newsgroups I
think it would be a terrible understatement to say you add a lot to the
development community but I'm not sure if I'm more impressed with your
extensive contribution or your ability to handle posters like this in a
calm and professional manner. I can only guess that you've worked with
(and cleaned up after) this sort of tunnel-visioned/short-sighted
developer before and take comfort in the fact that as long as his kind
exist, there will be a great demand for knowledgeable and skilled
engineers.
Just wanted you to know that your work here is greatly
appreciated by most of us; please keep it up.

Happy Holidays,
Will
 
S

seani

Ya know, I'd rather you not answer the question than tell me something
completely other than what I was asking about.

Ya know, he *did* address your question. You're just ignorant to
understand that he did.
1st off a struct is not in the least complex. 2nd I asked specifically
about speed. Not about design. It's a speed question, I don't care what
you think is a good use of design time.

It was a specific speed question, between a class object and a struct,
nothing else.
I don't get why people want to try and tell other people that there
questions aren't the right ones.

Can you post your full name and address so I can ensure that I never
accidentally employ you?
 
W

wackyphill

Why would you *not* want to know about other things which should affect
your decision, beyond the thing you happen to have thought of to start
with? Do you trust yourself to think of everything and have more
experience of the issues than everyone on the newsgroup? I know I don't
when I ask a question.

Because it was not a design decision, simply a curiosity of how the
run-time handles things.
For example, would a struct be more efficient if it was < 16 bytes and
an object be more efficient if > 16 bytes.
I'm curious about such things, despite their admitted irrelevance in
99% of most modern scenarios if all you're concerned w/ is getting
things to work.
From a knowing how things actually work perspective (if that interests
you as it does me) it is a valid question as it was worded IMO.
 
M

Mike Schilling

Ya know, I'd rather you not answer the question than tell me something
completely other than what I was asking about.

1st off a struct is not in the least complex.
2nd I asked specifically about speed. Not about design. It's a speed
question, I don't care what you think is a good use of design time.

Then I'll give you a speed answer:

Write some test cases. Time them. See what you find.

Since you're not interested in design issues, I won't waste your time
explaining what sorts of subtle and difficult-to-find bugs you'll encounter
when objects that logically should have reference semantics have value
semantics instead, because someone decided to "optimize".
 
W

wackyphill

ok.

Perhaps you guys should petition that structs be removed from the
language since you don't feel they are worth anyones time, and a
greater source of your bugs than a helpful addition to the programming
arsenal.
 
M

Mike Schilling

ok.

Perhaps you guys should petition that structs be removed from the
language since you don't feel they are worth anyones time, and a
greater source of your bugs than a helpful addition to the programming
arsenal.

Not at all. They're extermely useful for types that should have value
semantics, say, if you were going to implement complex numbers. But the
notion that using them is an optimization because they're "faster" is a
snare and a delusion.
 
J

Jon Skeet [C# MVP]

Perhaps you guys should petition that structs be removed from the
language since you don't feel they are worth anyones time, and a
greater source of your bugs than a helpful addition to the programming
arsenal.

If that were the case, I'd have just suggested not to use them at all.
Instead, I suggested (after answering your direct question, btw) that
speed of returning value should not be the determining factor when
deciding whether to use a struct or a class.
 
G

Guest

I'm with you, Sean - Please post this entire thread on any future resumes you
might produce, for it will be IMMENSELY helpful to an employer in guiding
them not make a serious mistake and hiring you, wackyphill!
 
J

Joanna Carter [TeamB]

<[email protected]> a écrit dans le message de (e-mail address removed)...

| Because it was not a design decision, simply a curiosity of how the
| run-time handles things.
| For example, would a struct be more efficient if it was < 16 bytes and
| an object be more efficient if > 16 bytes.

The difference of opinion that you have with Jon as to whether his advice
was relevant or not is stopping you from seeing that your question *cannot*
be answered in a straightforward A or B fashion.

The choice of class or struct should *never* be made on the basis of
efficiency, especially if that efficiency is counted in clock cycles.

A class is used because it suits all other purposes that cannot be served by
using a struct. So what if it takes a few nano-seconds extra; if you are
going to get the wrong design semantics and passing conventions, then what
is the point of using a struct, even if it is a smidgit faster ? I is also
not a question, of size; as Jon has said, it is much more about the design
choices made with regard to how the resulting type is going to be used. Sure
I could use a motorbike to get from A to B because it is faster than an
articulated lorry, but have you ever tried to carry 32 tonnes of potatoes on
the back of a motorbike ?

| I'm curious about such things, despite their admitted irrelevance in
| 99% of most modern scenarios if all you're concerned w/ is getting
| things to work.
| >From a knowing how things actually work perspective (if that interests
| you as it does me) it is a valid question as it was worded IMO.

Your curiosity is to be commended but, when an expert in the field lets you
know that the question is more complex than your original conceptions, then
you need to rethink whether the question was actually the right one to ask
:)

Joanna
 
B

Bruce Wood

First I'm going to "not answer" your question in the same way that Jon
did. Then I'll answer it, OK?

What would you think of someone who asked you which was faster, a flat
file or a database? What's the correct answer? What's the correct
answer if the usual reaction of someone who asks such a question is to
then run off and use flat files for everything, because they're
"faster"?

The answer, if course, is "it depends," and "one doesn't decide between
a flat file or a database based on speed, but based on any number of
other considerations." That's the answer you got from Jon. Given that
this topic comes up every couple of weeks here, couched in the exactly
the same terms, can you blame us for giving a big sigh and giving the
answer we did?

We discuss this issue all the time. You can read some background here

http://groups.google.com/group/micr...ges.csharp/browse_frm/thread/19815c2abf29d89f

and here

http://groups.google.com/group/micr...rp.general/browse_frm/thread/51ef2f65740a80e3

in a couple of threads in which I was involved.

Now that that's out of the way, here is the answer that I hope you're
after.

1. Structs are faster (and make more sense) if you want something that
will act like a value: like an int or a decimal. If you want it to
participate in comparisons and traditional calculations.

2. Structs are faster if they are involved in calculations that produce
large numbers of intermediate results. This is why (IMHO) Microsoft
chose to make Point and Rectangle as structs: they are both involved in
complex calculations that yield large numbers of intermediate results.

This latter point is because allocating all of those intermediate
results on the stack (with no need for later garbage collection) is
cheaper than allocating them on the heap (with the requisite garbage
collection afterward). However, the numbers of throw-away results have
to be pretty high to justify this.

On an e-commerce site, I assume that you have a database somewhere. I
can guarantee that you will spend 10,000 times as long getting things
in and out of a database than you would possibly ever save by fiddling
with structs versus classes to represent products.

If you want a good use for structs in your context, try this one: a
MonetaryAmount struct that contains a decimal quantity, a currency
code, and a DateTime, and knows how to convert itself into other
currencies.
 
S

seani

I'm with you, Sean - Please post this entire thread on any future resumes you
might produce, for it will be IMMENSELY helpful to an employer in guiding
them not make a serious mistake and hiring you, wackyphill!

It isn't particularly the question itself I'd be worried about; after all,
we all have areas where we "don't know what we don't know" as it were. But
that's easy to fix. I'd be more concerned about the attitude to someone
who clearly took time to give a considered answer.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top