Alfian
Alfian

Reputation: 43

Does calling a function that creates object cause memory leak?

Noob here. Let's say I made a function like this:

public void something()
{
   List<string> list = new List<string>();
}

Then I call something() 10x. Will it creates 10 objects of the same name or will it replaces with the new empty one so the object is still 1 in total? Does doing this would cause memory leak? Sorry for bad english.

Upvotes: 1

Views: 841

Answers (2)

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239684

Yes, it will create 10 new objects if called 10 times. No, this doesn't cause a memory leak1. One of the main points of working in a managed language with a garbage collector is that most of the time you don't have to think about how memory is being used2.

It's also good that each call creates a new instance of the List - because more and more these days, you'll have multiple threads running your program and you wouldn't want two calls that happen at the same time to interfere with each other's use of list.


1To properly be a memory leak in .NET, you need something long-lived to retain references to what should be short-lived objects, when it will never actually use those references. Local variables, such as here, have relatively short lives.

2And when you do care, you're much better off learning to use a memory profiler to see what memory is being used where.

Upvotes: 5

zolty13
zolty13

Reputation: 2231

No it does not cause memory leaks.

C# works on .Net Framework. Compiled .Net applications run in special environment called CLR (Common Language Runtime).

There is garbage collector in CLR which releases the memory for objects that are no longer being used by the application. Garbage collector works in background, so you do not have to worry about it.

If you want to you can call garbage collector manually: System.GC.Collect(), but it is not recommended. It is expensive to run. You must be abolutely sure that code is well written and you know what you are doing. Here is some examples: stack-clr-gc

Upvotes: 2

Related Questions