473,320 Members | 1,950 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Struct faster than class?

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?

Dec 23 '05 #1
17 3887
<wa********@yahoo.com> wrote:
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.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Dec 23 '05 #2
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.

Dec 23 '05 #3
<wa********@yahoo.com> wrote:
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*.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Dec 23 '05 #4
Jon Skeet [C# MVP] <sk***@pobox.com> wrote:
<wa********@yahoo.com> wrote:
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*.


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/iangblo...1/09/profiling

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Dec 23 '05 #5
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.

Dec 23 '05 #6
<wa********@yahoo.com> wrote:
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.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Dec 23 '05 #7
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

Dec 24 '05 #8
On Fri, 23 Dec 2005 15:03:13 -0800, wackyphill wrote:
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?

Dec 24 '05 #9
>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.

Dec 24 '05 #10

<wa********@yahoo.com> wrote in message
news:11*********************@g49g2000cwa.googlegro ups.com...
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".
Dec 24 '05 #11
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.

Dec 24 '05 #12

<wa********@yahoo.com> wrote in message
news:11**********************@g44g2000cwa.googlegr oups.com...
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.
Dec 24 '05 #13
<wa********@yahoo.com> wrote:
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.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Dec 24 '05 #14
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!

"seani" wrote:
On Fri, 23 Dec 2005 15:03:13 -0800, wackyphill wrote:
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?

Dec 24 '05 #15
<wa********@yahoo.com> a écrit dans le message de news:
11**********************@o13g2000cwo.googlegroups. com...

| 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

--
Joanna Carter [TeamB]
Consultant Software Engineer
Dec 24 '05 #16
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/micro...815c2abf29d89f

and here

http://groups.google.com/group/micro...ef2f65740a80e3

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.

Dec 24 '05 #17
On Sat, 24 Dec 2005 05:17:02 -0800, Jeff B wrote:
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.
"seani" wrote:
On Fri, 23 Dec 2005 15:03:13 -0800, wackyphill wrote:
> 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?


Dec 25 '05 #18

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

26
by: phoenix | last post by:
Hello, I've got a design question. I need to keep track of some variables and I am planning to put them inside a class or struct. Basically I'm talking about 10 bools, 20 ints and 2 arrays of...
5
by: Chua Wen Ching | last post by:
Hi there, I am very curious on this code: // declared as structure public struct Overlapped { public IntPtr intrnal; public IntPtr internalHigh;
2
by: Pohihihi | last post by:
After reading the thread "Struct faster than class?" I thought I should surely understand if I am doing anything wrong in my work. First, Jon you are very professional. Excellent. I will wish you...
16
by: Gerrit | last post by:
Hello, Is it possible to sort an array with a struct in it? example: I have a struct: public struct mp3file { public int tracknr;
46
by: clintonG | last post by:
Documentation tells me how but not when, why or where... <%= Clinton Gallagher http://msdn2.microsoft.com/en-us/library/saxz13w4(VS.80).aspx
7
by: Mantorok | last post by:
I've always followed a particular standard when considering structs, I mainly use a struct when a class isn't necessary (ie no requirement for multiple references). What is the recommendation...
37
by: JohnGoogle | last post by:
Hi, Newbie question... After a recent article in VSJ I had a go at implementing a Fraction class to aid my understanding of operator overloading. After a previous message someone suggested...
12
by: Author | last post by:
I know the basic differences between a struct and a class, but apparently not good enough to know why some types/concepts are implemented as struct whereas most types are implemented as class. For...
20
by: Plissken.s | last post by:
Is there an efficient way to create a struct of flag in C++? I need to create a struct of boolean flag, like this: struct testStruct { bool flag1; bool flag2; bool flag3; bool flag4; bool...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.