473,480 Members | 1,864 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Boxing Question

I am writing an app that might largely benefit from using a struct instead
of a class. However, it needs to be rich enough where there are methods
available.

My question is - every time you call a method on a struct, is it boxed?
Because that would be a huge perf hit.

I am assuming that it does have to be boxed, but if anyone knows for sure
that would be great!
Nov 16 '05 #1
10 1222
Nathan,
I am writing an app that might largely benefit from using a struct instead
of a class.
Why?

My question is - every time you call a method on a struct, is it boxed?


No

Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Nov 16 '05 #2
Hi Nathan,
I am writing an app that might largely benefit from using a struct instead
of a class.
There is little or no performance reason to prefer a struct over a class,
little or no efficiency reason, and little or no readability reason.
Structs are useful for making API calls to unmanaged code.

Structs are useful in only the smallest number of cases, and personally,
I've never used them in C# outside of unmanaged API calls. In fact, I've
never even _seen_ them used in the hundreds of thousands of lines of code
that have been delivered in the systems that I've overseen, reviewed, or
participated in.

--
--- Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster
http://blogs.msdn.com/nickmalik

Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I'm just a
programmer helping programmers.
--
"Nathan Neitzke" <ne******@erau.edu> wrote in message
news:%2****************@TK2MSFTNGP09.phx.gbl...
However, it needs to be rich enough where there are methods available.

My question is - every time you call a method on a struct, is it boxed?
Because that would be a huge perf hit.

I am assuming that it does have to be boxed, but if anyone knows for sure
that would be great!

Nov 16 '05 #3
>There is little or no performance reason to prefer a struct over a
class,
little or no efficiency reason


Correct me if I am wrong, but struct/value type in managed code is
mainly to improve performance. If you have large amount of data,
creating it on the stack is considerably less expensive than going on
the heap.

I have personally never used structs in my code (which is not really
saying much) but I have always been looking for some reason which will
justify it based solely from performance point of view. I have always
thought of the sceanrio where a large number of objects are getting
allocated/deallocated to be the driving force behind using a value type
in managed code.

---------
Ajay Kalra
aj*******@yahoo.com

Nov 16 '05 #4
"Nick Malik [Microsoft]" <ni*******@hotmail.nospam.com> wrote in message
news:Ip********************@comcast.com...
....
Structs are useful in only the smallest number of cases, and personally,
I've never used them in C# outside of unmanaged API calls. In fact, I've
never even _seen_ them used in the hundreds of thousands of lines of code
that have been delivered in the systems that I've overseen, reviewed, or
participated in.

I can think of cases where using classes instead of structs would make a
semantic difference. In the example below, if Currency was a reference type
the price of the product would be increased too, which is wrong:

lineItem.Price = product.Price;
lineItem.Price += new Currency(20, "CHF");

But as you Nick, I never saw it in real systems...
Alexander
Nov 16 '05 #5
Oops, it should be:

lineItem.Price = product.Price;
lineItem.Price += new Currency(20, "CHF");
Nov 16 '05 #6
Argh...

Something somewhere eats my plus signs!

Anyway it's the increment on the second line, "plus equals".

"Alexander Shirshov" <al*******@omnitalented.com> wrote in message
news:eT**************@tk2msftngp13.phx.gbl...
Oops, it should be:

lineItem.Price = product.Price;
lineItem.Price = new Currency(20, "CHF");

Nov 16 '05 #7
Nick Malik [Microsoft] <ni*******@hotmail.nospam.com> wrote:
I am writing an app that might largely benefit from using a struct instead
of a class.
There is little or no performance reason to prefer a struct over a class,
little or no efficiency reason, and little or no readability reason.
Structs are useful for making API calls to unmanaged code.


So you'd be happy if Int32 were a reference type, for example? I have
to disagree - the performance cost there would be dreadful. Imagine:

for (int i=0; i < 100000; i++)
{
....
}

You'd have created 100,000 objects on the heap, just for the iteration!
Structs are useful in only the smallest number of cases, and personally,
I've never used them in C# outside of unmanaged API calls. In fact, I've
never even _seen_ them used in the hundreds of thousands of lines of code
that have been delivered in the systems that I've overseen, reviewed, or
participated in.


I agree that they're very rarely useful outside interop, but they do
occasionally have their uses. I have two examples:

1) http://www.pobox.com/~skeet/csharp/t...ernative.shtml

2) Things which are units of measure. I've recently been writing some
code to do with coverage, and it's handy to have a Coverage struct
which is basically two ints ("total sequence points" and "hit sequence
points"). It's logically a value type in the same way that Int32 is,
and it's nice not to have to create a new (separate) object on the heap
every time I create one of them.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #8
Nathan,

I find that about boxing and unboxing always very interesting.

I made a simple test, can you try it.
In this test there is by the way 400,000,000 times a boxing or an unboxing
the results are milliseconds

{
int end1=0;
int end2=0;
for (int y = 0; y<1000;y++)
{
int start1 = Environment.TickCount;
for (object i=0; (int)i < 100000; i = (int) i + 1)
//This is very inefficient because the increment of the indexer
{
//Generated ILS code
//IL_000d: stloc.3
//IL_000e: ldc.i4.0
//IL_000f: box [mscorlib]System.Int32
//IL_0014: stloc.s i
//IL_0016: br.s IL_0029
//IL_0018: ldloc.s i
//IL_001a: unbox [mscorlib]System.Int32
//IL_001f: ldind.i4
//IL_0020: ldc.i4.1
//IL_0021: add
//IL_0022: box [mscorlib]System.Int32
//IL_0027: stloc.s i
//IL_0029: ldloc.s i
//IL_002b: unbox [mscorlib]System.Int32
//IL_0030: ldind.i4
//IL_0031: ldc.i4 0x186a0
//IL_0036: blt.s IL_0018
//IL_0038: ldloc.0
}
end1 += Environment.TickCount-start1;
int start2 = Environment.TickCount;
for (int i = 0; i < 100000; i++)
{
//Generated Ils code
//IL_003e: ldloc.3
//IL_003f: sub
//IL_0040: add
//IL_0041: stloc.0
}
end2 += Environment.TickCount-start2;
}
MessageBox.Show("Object: " + end1.ToString()
+ " Integer: " + end2.ToString());
}

Cor
Nov 16 '05 #9
I occassionaly return an error struct with a bool field.

Regards,
Jeff

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 16 '05 #10
Wow, great analysis. Thanks much for the code! Nice to see so IL in action
too. I like getting down to this level.

Actually, to reply to the posts above - they are right. In 99% of the
instances I would use a class instead of a struct.

However this is a very specialized case as I am writing a particular
algorithm for a scientific library. Just turns out that structs are more
efficient in this case.

Thanks again!

--
Nathan
"Cor Ligthert" <no************@planet.nl> wrote in message
news:eq**************@TK2MSFTNGP12.phx.gbl...
Nathan,

I find that about boxing and unboxing always very interesting.

I made a simple test, can you try it.
In this test there is by the way 400,000,000 times a boxing or an unboxing
the results are milliseconds

{
int end1=0;
int end2=0;
for (int y = 0; y<1000;y++)
{
int start1 = Environment.TickCount;
for (object i=0; (int)i < 100000; i = (int) i + 1)
//This is very inefficient because the increment of the indexer
{
//Generated ILS code
//IL_000d: stloc.3
//IL_000e: ldc.i4.0
//IL_000f: box [mscorlib]System.Int32
//IL_0014: stloc.s i
//IL_0016: br.s IL_0029
//IL_0018: ldloc.s i
//IL_001a: unbox [mscorlib]System.Int32
//IL_001f: ldind.i4
//IL_0020: ldc.i4.1
//IL_0021: add
//IL_0022: box [mscorlib]System.Int32
//IL_0027: stloc.s i
//IL_0029: ldloc.s i
//IL_002b: unbox [mscorlib]System.Int32
//IL_0030: ldind.i4
//IL_0031: ldc.i4 0x186a0
//IL_0036: blt.s IL_0018
//IL_0038: ldloc.0
}
end1 += Environment.TickCount-start1;
int start2 = Environment.TickCount;
for (int i = 0; i < 100000; i++)
{
//Generated Ils code
//IL_003e: ldloc.3
//IL_003f: sub
//IL_0040: add
//IL_0041: stloc.0
}
end2 += Environment.TickCount-start2;
}
MessageBox.Show("Object: " + end1.ToString()
+ " Integer: " + end2.ToString());
}

Cor

Nov 16 '05 #11

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

Similar topics

14
323
by: Lora Connors | last post by:
What is Boxing & UnBoxing in .NET?
4
1700
by: Alistair Welchman | last post by:
I have a Hashtable of ints keyed on Guids, and I want to do the following: foreach ( DataRow row in dsWorkDays.Tables.Rows ) { Guid PersonId = (Guid)row; DateTime Day = (DateTime)row;
43
6842
by: Mountain Bikn' Guy | last post by:
I have a situation where an app writes data of various types (primitives and objects) into a single dimensional array of objects. (This array eventually becomes a row in a data table, but that's...
5
1748
by: Craig | last post by:
Hi everyone, As a relative new-comer to the wonderful world of .NET Framework and the C# langauge I have come across something that I would like to clarify (hopefully with the help of kind...
1
2202
by: Tom | last post by:
Couple of questions relating to boxing. Firstly, I already know that boxing is the processing of temporarily copying a ValueType (e.g. struct, enum) to the heap so that the system can treat a...
7
1468
by: J.Marsch | last post by:
Hello all: I am trying to introduce the concept of boxing (and some of the hang-ups) to some developers that are coming onto a project. A while back, I read a really cool article that was...
24
2569
by: ALI-R | last post by:
Hi All, First of all I think this is gonna be one of those threads :-) since I have bunch of questions which make this very controversial:-0) Ok,Let's see: I was reading an article that When...
94
5575
by: Peter Olcott | last post by:
How can I create an ArrayList in the older version of .NET that does not require the expensive Boxing and UnBoxing operations? In my case it will be an ArrayList of structures of ordinal types. ...
19
13675
by: ahjiang | last post by:
hi there,, what is the real advantage of boxing and unboxing operations in csharp? tried looking ard the internet but couldnt find any articles on it. appreciate any help
161
7683
by: Peter Olcott | last post by:
According to Troelsen in "C# and the .NET Platform" "Boxing can be formally defined as the process of explicitly converting a value type into a corresponding reference type." I think that my...
0
7055
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7059
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7103
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
7010
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
1
4799
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new...
0
4499
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3011
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
1
572
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
203
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

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.