Quantcast
Channel: .NET Framework Class Libraries forum
Viewing all articles
Browse latest Browse all 8156

Strings and their memory utilization

$
0
0

I have two questions about strings

1> When we pass string as a parameter, and if the same string value is getting passed to different methods, and since strings are immutable, will .Net run time creates new instance of string every time it passes through those methods.
For example below

public class Service
{
    public void Run(string largeString)
	{
			logger.LogLargeStringToFileSystem(largeString);

			// call private method
			DoPrepWork(largeString);

			validator.Validate(largeString);

			repository.Save(largeString);
	}

	private void DoPrepWork(string largeString)
	{
	}
}


public class Validator
{
   public void Validate(string largeString)
   {
   }
}

public class Repository
{
   public void Save(string largeString)
   {
   }
}

public class Logger
{
   public void LogLargeStringToFileSystem(string largeString)
   {
      // log string to file system
   }
}

2>Can we set string to null to free up the memory? I know garbage collector eventually collects the string but I think it happens when the control goes out of the scope.So in the code below, I don’t need string variable as soon it gets converted to object. How do I immediately free up the memory occupied by the string variable. I dont want to use GC.Collect() everywhere in the code

public class Service
{
    public void Run(string largeString)
	{

			MyObject obj = ConvertToObject(largeString);

			//i dont need largeString anymore
			// the long running task may take time, so i would like to free up memory as soon as possible

			worker.DoLogRunningTask(obj);
	}
}


public class Worker
{
   public void DoLongRunningTask(MyObject obj)
   {
   }
}



Viewing all articles
Browse latest Browse all 8156

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>