Why are Arrays reference types? [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
int[] age=new int[5];
After reading many posts and blogs ,I am still not clear about the fact why arrays are reference types.I know this question is like very old and have been asked plenty times but still couldnt find direct answer.
Known things :Since Arrays are allocated on heap,hence they are reference types .
Need to know:Whats the reason behind making(compiler) arrays as reference types?.
Suppose age[0]=5,age[1]=25 ,what is the difficulty in assigning these on stack or make reference to heap if their type was object.why consider heap as accessing time is slow comparatively?.
Why heap ,why not on stack like for structures?.

Several reasons:
value types are passed by value (as in copied). So if you called a method with a value-type array, you'd be copying all the contents.
Stack memory is limited and primarily designed for quick access to parameters that are in current use (as implied by the term stack). Putting a large object onto the stack would cause lookups of other local state to take much longer, because they wouldn't all be on the same cache line in the CPU cache anymore.
Array contents are modifiable. So you'd have all the issues that you have with mutable structs when you tried to set a value, only to find that the copy, not the "original" was modified.
EDIT:
Yes you can use stackalloc in unsafe code. Doesn't make it a good idea.

Related

Does ImmutableList have AsReadOnly like method? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
AsReadOnly() is a convenient method to get a read-only image (not expensive compared to immutable collections' copies) of a collection. I am wondering if ImmutableList has AsReadOnly like method? If no, any easy way to implement similarly?
Immutable collections are inherently read-only. You can easily check in the documentation that ImmutableList<T> already implements IReadOnlyList<T> and IReadOnlyCollection<T> interfaces.
Memory is not allocated when you access elements from immutable collection. On the other hand, when you add an element to some immutable data structure, a new immutable collection is created (and some memory is used). Many immutable collections' implementations do not copy all the data to a new collection but instead share some data from with the old one, so in most cases you should not be too concerned with memory usage/allocation time.
Some collections, e.g. ImmutableHashSet<T>, have a documentation which states that they are optimized in terms of number of memory allocations.
The idea behind sharing some data between immutable collection is not complicated. Wikipedia has an simple example (with a nice diagram) showing how memory can be saved in case of immutable singly-linked lists.
ImmutableList<T> is copied by reference so is perfectly safe to pass around without a performance penalty. Thus there is no need for an AsReadOnly method as it wouldn't make it any easier to copy.

Best way to pair a Pre-made Class and primitive type C# [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Basically, I'm wanting to efficiently pair multiple bool and bytes ( to store values ) with a pre-made class (RenderTarget2D if you must know).
Obviously, I can wrap this all in a class, however there are situations when I will be having many of these, and would like to save on memory where possible (ie use a struct).
I know it's bad behaviour to use a struct with reference variables, and I'd prefer not to just use separate variables to hold the information ( would rather pair it all together ).
Essentially I am wanting a structure to hold a reference to a class, a bool, and a byte, and create a 2D array of this to make many (thus am looking for a mitigate memory usage)
Am I overlooking an obvious solution?
Understanding the question as:
You want something that holds a bool, a byte and an instance of the class RenderTarget2D.
If that is the case you can use Tuple<bool, byte, RenderTarget2d>.
Creating a custom class or struct is also a viable option. In fact there is a proposal for "C# 7" to include language native tuples (that will not be System.Tuple) and as currently written, they will be structs.
You may also want to consider that having a reference to the RenderTarget2d may prolong its lifespan.
Struct vs Class
The struct takes in memory (when compacted) the size of a bool plus the size of a byte plus the size of a reference (to RenderTarget2d). If you have an array of 600 by 600 (360000) of such structs it takes 360000 the size of the struct in memory.
If you use classes, the array will have 360000 references to the actual location of the data that in total takes at least as much as the array of structs.
So using the structs should take less memory...
But when you take a struct from your data structure, you are actually making a copy. So each time you access your array to get a item and read a property of that item, you are actually making a copy of the item and reading the property from that copy.
If you want to update it, you need to read it (that makes a copy as mentioned above) edit it, and then put it back... and that copies the data to the array.
So, if the memory is the main concern. Use struct. To quote Jon Skeet: "so long as you're aware of the consequences".
Using struct also means less RAM round trips. Not only because it avoids resolving the references, but also because the data is guaranteed to be close together. This allows for better performance because the CPU will load a chunk (or the totality) of the data structure in cache and since the code is not using references outside of that it will be able to keep it in cache instead of going to load another thing.

Is it safe to access a method of C# from an unmanaged C library? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm accessing a method of C# from C now. Below is some snippet of code in C#.
IntPtr pFunc = Marshal.GetFunctionPointerForDelegate (
new DelegateForMyMethodInCsharp (
MyMethodInCsharp
)
);
setFuncPtr(pFunc);
setFuncPtr() is a function of a C library to set the pointer of a C# method. After this code I can call the C# method in the C library whenever I want without any problems but I'm not sure if this is okay.
When using pointers for variables stored in heap in C#, the keyword 'fixed' must be used due to GC. Because the stack section of memory contains methods, it makes sense for me to write code like above. But because I haven't seen people write that way yet, I hope to hear your opinions.
This is a very simple question, but a very important question to me.
I don't want to write unsafe code.
You need to make sure that the delegate instance is not garbage collected.
To do that, you can simply store it in a field, and make sure that field is rooted for as long as the unmanaged code hangs on to the pointer.
This is necessary because delegates store not just a pointer to a .Net method, but also state (the first argument; typically this). To make a function pointer for that, the runtime must create a thunk that refers to this object, so that unmanaged code can get there from nothing but a function pointer. This is bounded by the lifetime of the delegate instance.
For more information on the difference between delegates and function pointers, see my blog.

Independent Variables and Array performance [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I would like to know what is more optimal, A number N of private integer variables, or a single array containing N integer values.
When you use an array, that is a plus indirection. The array will be allocated at a separate part of the memory, so when you first access it, your code first obtains its address, then it is able to read out its content. It also needs some indexing, but that is done extremly fast by the CPU. However, .NET is a safe environment and it will do a check whether you use a valid array index. It adds additional time.
When you use separate variables, these will be encompassed by your object instance and no indirection is needed. Also, no index bound check is needed.
Moreover, you cannot name nicely the Nth element of an array, but you can give good names for individual variables. So your code will be readable.
As others mentioned, you shouldn't do this kind of optimalizations, the compiler/jitter take care of it. The compiler knows several common use cases and has optimialization strategy for that. If you start doing tricky things, the compiler will not recognize your intention and cannot make the optimalization for you.

Allocated on the heap or the stack? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I recently asked a question about StackOverflowExeptions and the explanations were very helpful!
However, I wrote a method and tried to figure out where T cached is allocated (heap/stack):
private Dictionary<Type, Component> _cachedComponents = new Dictionary<Type, Component>();
public T GetCachedComponent<T>() where T : Component {
//Not yet sure if the next line works or throws an exception -> just ignore it
if(_cachedComponents[typeof(T)] != null) {
return (T)_cachedComponents[typeof(T)]
} else {
T cached = this.GetComponent<T>();
_cachedComponents.Add(typeof(T), cached);
return cached;
}
}
Since T cached is declared inside the method I assume it is allocated on the stack, right?
But the reference is then added to the dictionary, wich should be allocated on the heap, right?
The stack is "cleared" after the method returns, right?
But what happens to T cached? Is it going to be moved to the heap? (Because the stack does not "carry the data" anymore but the dictionary still holds a reference)
Since T cached is declared inside the method I assume it is allocated
on the stack, right?
T being allocated in a method doesn't effect it being on the heap or the stack. The decision whether it is the former or the latter is based on whether this is a reference type or a value type.
But the reference is then added to the dictionary, wich should be
allocated on the heap, right?
Once the reference is added to the Dictionary<TKey, TValue>, the key will be stored inside the dictionary, which is allocated on the heap, as it is a reference type.
The stack is "cleared" after the method returns, right?
The stack frame is cleared once the method returns.
But what happens to T cached? Is it going to be moved to the heap?
If T is cached inside the dictionary, then it is already allocated on the heap.
Overall, I assume you ask these questions as for general knowledge. You shouldn't be worrying about this too much, as what I wrote here is an implementation detail and is subject to change.

Categories