473,836 Members | 1,512 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Can't assign value to structure in array?

I have created a structure with five fields. I then create an array of this
type of structure and place the structure into an array element. Say index
one. I want to assign a value to field3 of the structure inside the array.
When I try this, an error about late assignment appears. Is it possible to
assign a value to a structure field that is in an array?

I'm currently getting around the problem by creating a new structure, assign
the structure fields using values in the arary...minus field 3, which gets a
value from somewhere else. I then place this structure into the array.

Thanks,
Brett
Nov 17 '05
26 7105
> The increased memory usage of an array of object references (8 bytes heap
overhead per object + 4 bytes per array element pointer) decreases
locality of reference, which also impacts performance.
I still don't think the dereference is significant, but I buy the locality
argument. A poorly timed page fault and everything goes to hell.

--
Jonathan Allen
"Frank Hileman" <fr******@no.sp amming.prodiges oftware.com> wrote in message
news:%2******** *******@TK2MSFT NGP15.phx.gbl.. . If a loop is not a bottleneck -- why discuss performance? Let us assume
the developer can determine bottlenecks.

Yes, a single pointer dereference has made a critical difference in code I
have written. This type of code is common in graphics libraries,
mathematics libraries, processing huge data sets, scientific applications,
collection libraries, etc.

The increased memory usage of an array of object references (8 bytes heap
overhead per object + 4 bytes per array element pointer) decreases
locality of reference, which also impacts performance. Consider an 8 byte
struct. Substitute a class, and you have increased memory usage by 150%.
If you have an array with 100K elements, the struct version uses 800K
bytes, and the object version uses 2 meg. These types of differences can
push you out of a fast cache limit.

Structs in arrays can be sorted. If a struct is the same size as a
pointer, it is the same cost to copy. If used improperly large structs can
be a problem, but that is no reason to ban mutable structs. A better
approach would be to fix the language, so that a struct copy can be easily
distinguished from a reference (pointer) copy, reducing confusion.

Consider a struct with 8 properties, each internally consuming one byte of
storage. Suppose you need to modify one property. If the struct is
immutable, you must "modify" it by copying all 8 property values to a
constructor for a new struct taking 8 arguments. If the struct is mutable
the code is much simpler -- just change the property. So it is not just a
performance argument.

Frank

Nov 17 '05 #21
The object is stored on the heap and GC takes place there. Is the struct
stored on the stack? I'd assume it is since it is value type. Also, how is
the stack cleared? By GC?

Thanks,
Brett

"Frank Hileman" <fr******@no.sp amming.prodiges oftware.com> wrote in message
news:%2******** *******@TK2MSFT NGP15.phx.gbl.. .
If a loop is not a bottleneck -- why discuss performance? Let us assume
the developer can determine bottlenecks.

Yes, a single pointer dereference has made a critical difference in code I
have written. This type of code is common in graphics libraries,
mathematics libraries, processing huge data sets, scientific applications,
collection libraries, etc.

The increased memory usage of an array of object references (8 bytes heap
overhead per object + 4 bytes per array element pointer) decreases
locality of reference, which also impacts performance. Consider an 8 byte
struct. Substitute a class, and you have increased memory usage by 150%.
If you have an array with 100K elements, the struct version uses 800K
bytes, and the object version uses 2 meg. These types of differences can
push you out of a fast cache limit.

Structs in arrays can be sorted. If a struct is the same size as a
pointer, it is the same cost to copy. If used improperly large structs can
be a problem, but that is no reason to ban mutable structs. A better
approach would be to fix the language, so that a struct copy can be easily
distinguished from a reference (pointer) copy, reducing confusion.

Consider a struct with 8 properties, each internally consuming one byte of
storage. Suppose you need to modify one property. If the struct is
immutable, you must "modify" it by copying all 8 property values to a
constructor for a new struct taking 8 arguments. If the struct is mutable
the code is much simpler -- just change the property. So it is not just a
performance argument.

Frank

"Jonathan Allen" <x@x.x> wrote in message
news:OZ******** ******@TK2MSFTN GP10.phx.gbl...
?? Every pointer dereference, every instruction, counts in a tight loop


Not true. If the loop isn't the bottleneck in your application, it
doesn't matter what is going on in it.

Honestly, can you think of a single time in your entire life that an
extra dereference in a loop actually made the difference between a usable
and unusable program?

Another consideration is what you are going to do with your N structs.
Will they really live solely in that array? Are you never going to sort
it? Are you never going to return a subset from a function call?

I'm asking because the first time you copy those structs to another
location, you've already lost your gain several times over. Copying a
struct is far more expensive than copying a pointer.

--
Jonathan Allen


Nov 17 '05 #22
Brett <no@spam.com> wrote:
The object is stored on the heap and GC takes place there. Is the struct
stored on the stack? I'd assume it is since it is value type. Also, how is
the stack cleared? By GC?


Structs in arrays are stored on the heap (for most .NET applications
anyway; there are ways of storing arrays on the stack in C# and
presumably in C++ too). The stack isn't cleared by the garbage
collector - it's just cleared when the stack is popped. No data which
is on the stack is available after the stack is popped, so there's no
need for a complex system like garbage collection.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #23
> The object is stored on the heap and GC takes place there. Is the struct
stored on the stack? I'd assume it is since it is value type. Also, how
is the stack cleared? By GC?
The stack is cleared when the function exits. Think of it as a stack of
boxes, the currently running function uses the top-most box. The function
that called it uses the next box. etc. Each box is created with enough room
to hold all the locals declared in the function.

Structs can be stored in the stack or inside a class. Or they can be boxed
and stored as if they were a class.

--
Jonathan Allen
"Brett" <no@spam.com> wrote in message
news:Oz******** ******@TK2MSFTN GP12.phx.gbl... The object is stored on the heap and GC takes place there. Is the struct
stored on the stack? I'd assume it is since it is value type. Also, how
is the stack cleared? By GC?

Thanks,
Brett

"Frank Hileman" <fr******@no.sp amming.prodiges oftware.com> wrote in
message news:%2******** *******@TK2MSFT NGP15.phx.gbl.. .
If a loop is not a bottleneck -- why discuss performance? Let us assume
the developer can determine bottlenecks.

Yes, a single pointer dereference has made a critical difference in code
I have written. This type of code is common in graphics libraries,
mathematics libraries, processing huge data sets, scientific
applications, collection libraries, etc.

The increased memory usage of an array of object references (8 bytes heap
overhead per object + 4 bytes per array element pointer) decreases
locality of reference, which also impacts performance. Consider an 8 byte
struct. Substitute a class, and you have increased memory usage by 150%.
If you have an array with 100K elements, the struct version uses 800K
bytes, and the object version uses 2 meg. These types of differences can
push you out of a fast cache limit.

Structs in arrays can be sorted. If a struct is the same size as a
pointer, it is the same cost to copy. If used improperly large structs
can be a problem, but that is no reason to ban mutable structs. A better
approach would be to fix the language, so that a struct copy can be
easily distinguished from a reference (pointer) copy, reducing confusion.

Consider a struct with 8 properties, each internally consuming one byte
of storage. Suppose you need to modify one property. If the struct is
immutable, you must "modify" it by copying all 8 property values to a
constructor for a new struct taking 8 arguments. If the struct is mutable
the code is much simpler -- just change the property. So it is not just a
performance argument.

Frank

"Jonathan Allen" <x@x.x> wrote in message
news:OZ******** ******@TK2MSFTN GP10.phx.gbl...
?? Every pointer dereference, every instruction, counts in a tight loop

Not true. If the loop isn't the bottleneck in your application, it
doesn't matter what is going on in it.

Honestly, can you think of a single time in your entire life that an
extra dereference in a loop actually made the difference between a
usable and unusable program?

Another consideration is what you are going to do with your N structs.
Will they really live solely in that array? Are you never going to sort
it? Are you never going to return a subset from a function call?

I'm asking because the first time you copy those structs to another
location, you've already lost your gain several times over. Copying a
struct is far more expensive than copying a pointer.

--
Jonathan Allen



Nov 17 '05 #24
We were talking about structs in arrays. Those would always be on the heap,
not the stack. If you are talking about a value type used as a parameter or
local variable, or a temporary returned by an operator overload, then you
are potentially looking at the stack.

The stack is allocated according to the number and size of parameters, local
variables, and temporaries used by a method. When the method returns the
stack space is immediately released and reused for the next method call.
Basically it is just a preallocated block of memory with the current offset
kept in a register than is incremented and decremented. Often temporaries,
local variables, and parameters wind up in registers instead, and take no
space on the stack. This is the ideal situation.

The .NET GC is fast. But it can never beat the memory size and speed of
value types in local variables or parameters, as they may be in registers.
Even if they are on the stack, the .net heap allocater continues to move
into new memory addresses as it allocates new objects, until a GC is
triggered, whereas the stack constantly reuses a smaller area of memory, so
you get better locality of reference. The .NET allocator and GC are so fast
sometimes the heap seems similar to a stack over a larger span of memory.
Look at the timeline view in the CLRProfiler tool.

Regards,
Frank Hileman

"Brett" <no@spam.com> wrote in message
news:Oz******** ******@TK2MSFTN GP12.phx.gbl...
The object is stored on the heap and GC takes place there. Is the struct
stored on the stack? I'd assume it is since it is value type. Also, how
is the stack cleared? By GC?

Thanks,
Brett

Nov 17 '05 #25
> My point is that the structure is access only three times. Two writes and
one read. This isn't complicated and I don't have to worry about
accidentally assigning a value to the structure while it is being read
somewhere else. That can't happen since the flow is procedural.
I believe that is the red flag some of you were thinking about.


The "red flag" has nothing to do with concurrency. It has instead to do
with semantics. What's missing in this conversation is that nowhere
have you indicated why you _need_ a struct, rather than a class.
structs in C# are very useful, but they are useful for specific reasons
in specific situations. Nothing you've outlined so far indicates that
you're in one of those situations. You may be, but we just haven't
heard why you need a struct here.

So when do you _need_ a struct?

First and foremost, you need a struct when you need something that will
act like a native (value) type: whenever you assign it, it gets copied.
When you pass it as a method argument, it gets copied. In general you
don't care about the _identity_ of the thing: this-one-versus-that-one;
all you really care about its its _value_ (thus the name). Some
examples of structs I've created: a Fraction class, a Measure class
that holds a quantity and a unit of measure. In both of these cases,
Fractions and Measures act like values, like ints or doubles. I don't
_want_ to have a specific instance of 3 3/4 somewhere, with everyone
pointing to it and modifying it. When I assign a Fraction to a variable
I want to create a new Fraction with the same value.

Second, and less common, you may choose to use a struct to improve the
efficiency of your application. This is the one that gets everyone into
trouble with structs.

A word about efficiency: CPU-intensive applications aside (and there
aren't many of those... really, there aren't), you get far, far more
bang for your buck looking for efficiencies in your program's _design_
than you ever will tweaking code. Yes, there are some areas of
programming where both design and tweaking code are required, but as I
said, not many. It's hard to convince newbies of this. So many new
programmers just _love_ poring over their code, tweaking an instruction
here, eliminating a variable there, obvlivious to the fact that there
are huge gains to be had by modifying design or data structures, and
that all of that hand-work they're doing was probably done by the
compiler or the JITter, anyway.

In C#, this manifests itself as a mad dash to turn things into structs
that really have no business being structs, so that the program will be
"more efficient." It also manifests itself as odd questions in
newsgroups, questions like, "Why would anyone want to use a class if
they're less efficient?" A little knowledge, as the saying goes, is a
dangerous thing.

Of course, in using a struct where a class is really needed, one has to
make the struct mutable (give it set accessors), and then the trouble
really starts.

The "red flag" that Ted Miller mentioned is this: structs are useful,
but you don't often run across situations in which you need them. If
you don't need a struct, you're probably better off using a class,
particularly if you don't have a solid understanding of value semantics
versus reference semantics. The problems you're having are likely an
indication that you really want a class, not a struct.

Furthermore, if you create a mutable struct (a struct with settable
properties), then you had better have a _very_ solid understanding of
value semantics and how they differ from reference semantics.
Otherwise, you're going to find strange things happening in your code,
and the few cycles you may have saved by using a struct (if you save
any at all) will be offset by the hours of head-scratching you'll
endure trying to get your program to work. (The upside is that once
you've gone through that pain, you'll either hate structs or have a
solid understanding of value semantics--or both.)

I would make the same claim about exposing mutable structs as part of
the public contract of a DLL for others' use. You had better be sure
that your callers have a _solid_ understanding of .NET value semantics.
Either that or be ready with arguments as to why you had to make
mutable structs publicly visible. Yes, I know that Microsoft did it.
They had very good reasons why they did it. Nonetheless, it still
confuses the %&$# out of a lot of programmers.

Use classes. Use structs only when classes won't do.

Nov 17 '05 #26
> My point is that the structure is access only three times. Two writes and
one read. This isn't complicated and I don't have to worry about
accidentally assigning a value to the structure while it is being read
somewhere else. That can't happen since the flow is procedural.
I believe that is the red flag some of you were thinking about.


The "red flag" has nothing to do with concurrency. It has instead to do
with semantics. What's missing in this conversation is that nowhere
have you indicated why you _need_ a struct, rather than a class.
structs in C# are very useful, but they are useful for specific reasons
in specific situations. Nothing you've outlined so far indicates that
you're in one of those situations. You may be, but we just haven't
heard why you need a struct here.

So when do you _need_ a struct?

First and foremost, you need a struct when you need something that will
act like a native (value) type: whenever you assign it, it gets copied.
When you pass it as a method argument, it gets copied. In general you
don't care about the _identity_ of the thing: this-one-versus-that-one;
all you really care about its its _value_ (thus the name). Some
examples of structs I've created: a Fraction class, a Measure class
that holds a quantity and a unit of measure. In both of these cases,
Fractions and Measures act like values, like ints or doubles. I don't
_want_ to have a specific instance of 3 3/4 somewhere, with everyone
pointing to it and modifying it. When I assign a Fraction to a variable
I want to create a new Fraction with the same value.

Second, and less common, you may choose to use a struct to improve the
efficiency of your application. This is the one that gets everyone into
trouble with structs.

A word about efficiency: CPU-intensive applications aside (and there
aren't many of those... really, there aren't), you get far, far more
bang for your buck looking for efficiencies in your program's _design_
than you ever will tweaking code. Yes, there are some areas of
programming where both design and tweaking code are required, but as I
said, not many. It's hard to convince newbies of this. So many new
programmers just _love_ poring over their code, tweaking an instruction
here, eliminating a variable there, obvlivious to the fact that there
are huge gains to be had by modifying design or data structures, and
that all of that hand-work they're doing was probably done by the
compiler or the JITter, anyway.

In C#, this manifests itself as a mad dash to turn things into structs
that really have no business being structs, so that the program will be
"more efficient." It also manifests itself as odd questions in
newsgroups, questions like, "Why would anyone want to use a class if
they're less efficient?" A little knowledge, as the saying goes, is a
dangerous thing.

Of course, in using a struct where a class is really needed, one has to
make the struct mutable (give it set accessors), and then the trouble
really starts.

The "red flag" that Ted Miller mentioned is this: structs are useful,
but you don't often run across situations in which you need them. If
you don't need a struct, you're probably better off using a class,
particularly if you don't have a solid understanding of value semantics
versus reference semantics. The problems you're having are likely an
indication that you really want a class, not a struct.

Furthermore, if you create a mutable struct (a struct with settable
properties), then you had better have a _very_ solid understanding of
value semantics and how they differ from reference semantics.
Otherwise, you're going to find strange things happening in your code,
and the few cycles you may have saved by using a struct (if you save
any at all) will be offset by the hours of head-scratching you'll
endure trying to get your program to work. (The upside is that once
you've gone through that pain, you'll either hate structs or have a
solid understanding of value semantics--or both.)

I would make the same claim about exposing mutable structs as part of
the public contract of a DLL for others' use. You had better be sure
that your callers have a _solid_ understanding of .NET value semantics.
Either that or be ready with arguments as to why you had to make
mutable structs publicly visible. Yes, I know that Microsoft did it.
They had very good reasons why they did it. Nonetheless, it still
confuses the %&$# out of a lot of programmers.

Use classes. Use structs only when classes won't do.

Nov 17 '05 #27

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

Similar topics

6
644
by: Ram Laxman | last post by:
Hi all, Can I assign an array to a vector if both(array and vector) holds same data type?
7
6631
by: baumann | last post by:
hi all, #include "stdafx.h" struct a_{ int a; int b; };
0
1802
by: JJ_377 | last post by:
The following doesn't assign value to the dropdownlist - WHY? ___________________________________________________________________ In a user control (ascx named USACustomer) : Public Property State() As String Get Return Me.ddlState.SelectedValue End Get Set(ByVal Value As String)
7
2047
vikas251074
by: vikas251074 | last post by:
Can I assign value to cookies immediately after selecting a value from list? <select name="vlan_name" style="width:150px "> <%set rs = conn.execute("select vlan_name from vlan_master order by vlan_name") dim v_lan do while not rs.eof%> <option value="<%=rs("vlan_name")%>"><%=rs("vlan_name")%></option> <% rs.movenext loop%> </select>
17
9623
by: zombiezoom | last post by:
I need help with error 2448: You can't assign value to this object. What I am trying to do is allow user to select event id and race id from combo option. Once the user selects those, then the id associated with those is suppose to be carried over to a new form which should associated those two ids with runner id from runner table. Thus, I will have all three ids in event-race-runner table (which is an associative table). However when I do that...
0
9825
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9671
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10595
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9379
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7793
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6979
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5650
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5828
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3116
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 can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.