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.
Related
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 last month.
Improve this question
I need a buffer of memory which holds actual objects, not references, in memory.
I am using Unity Engine for my app. In order to submit a draw-call in Unity, one must provide a Mesh-object and Material-object in the function call. Here
is the part of my algorithm I am trying to optimize.
Mesh[] meshes;
Material[] materials;
Foreach (mesh-type)
DrawMeshInstancedIndirect(mesh[i],material[i]...etc);
I want to be able to iterate over a buffer of memory directly containing the object data, with no references, because I don't want to fill my cpu cache with useless data fetching each object in random parts of memory. You cannot substitute structs for these special Unity classes.
It doesn't matter if it is bad practice or a very messy solution. This is a performance-critical part of my app where structs cannot be substitute for classes.
Here is a reference to the draw-call function, for more context.
https://docs.unity3d.com/ScriptReference/Graphics.DrawMeshInstancedIndirect.html
Try the fixed keyword.
class Foo
{
public int[] stuff = new int[999];
public unsafe void ExamplePinned()
{
fixed (int* pStuff = stuff)
{
//Alright, the data array is all set and ready to go. Think of 'pStuff' as a pointer
//to the first element in the array. You can use it to access the memory of the
//array and copy it to another buffer
}
}
}
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 4 years ago.
Improve this question
My question is what happen in memory when we create two object for one class variable.
For example:
class a = new class();
a = new class();
At that time, are both allocated in same memory
Two objects are allocated on the heap. The first one is replaced by the one from the second statement, and will be deallocated by the garbage collector when there's sufficient memory pressure that necessitates a collection.
class a = new class();
This will create two things: an instance of the class on the heap, and a reference a to that instance.
a = new class();
This will create a new instance of the class on the heap, and change the reference a to point to the new instance. The previous instance will remain in memory but be inaccessible without any other reference to it (aka. refcount of 0) and will be cleaned up by the garbage collector when it runs.
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.
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
In c# When does the memory allocation in Stack/Heap occurs. Is it during the runtime or compile time. From my study I understand that all memory allocations happens during run time for both value type and reference type. Is this correct?
How would it happen during compile-time ? The program is not yet running and there is no need to allocate memory before the program run. It is common sense that this should happen at run-time (When actually executing the generated IL).
Memory management it also optimized that it may not happen when you just create the variable, but when you first use it.
I think you might be confusing the actual allocation, which can only happen at runtime when the program is actually running, with the allocation calculation/determination. For example, consider the following method:
void Foo()
{
int i = 42;
Console.WriteLine(i);
}
The compiler will now statically (compile-time) that i will require 4 bytes of space on the stack. However, it will not be until the program actually runs that the actual allocation takes place.
Moreover, the above method won't even be compiled into machine code (a prerequisite for any operation such as allocation) until the CLR loads the code and passes it to the JIT (Just in Time compiler). Of course, even if it did, it's not until the actual process is created that the OS even allocates a memory address space for it to use...
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.