Compartir a través de


String.Intern() method implements FlyWeight pattern for better Performance and reduces MemoryFootprint.

As we all know String is a reference type in Dotnet and what we dont know is how it will effectively manages Memory by using Flyweight Pattern for  String.Intern() method .

What is exactly Flyweight pattern do ? 

 1)  Reduce Storage Costs for Large number of objects 

  2) share objects to be used in Multiple contexts simultaneously , but still maintains object oriented granularity and flexibility . 

Suppose there is a requirement to implement "BRICK" class for building an Apartment, there might involve many Bricks During Construction . Here generally, user end up Creating milions of Brick Objects for building single room and this has to be repeated in building entire Apartment .  [ though different sizes of bricks may be used ] . 

Here complexity increases in creating more number of similar objects , flyweight pattern comes to rescue at this position . 

Using FlyWeight pattern, group of shared objects are replaced by few shared objects once Extrinsic State[ like brick dimensions ]  is removed . Dividing the states and seperating them into intrinsic and extrinsic state is important in flyweight pattern . this will improve performance and reduces complexity and memory footprint.

To give you more details , let us consider a small example on this   

Case 1 :  

consider 2 strings 

String s1= "Santhosh" ;

String s2= s1 ; // as we know strings are reference type so both s1 and s2 will be pointing to the same address location 

Console.WriteLine( ReferenceEquals(s1,s2)); // returns True .

Case 2 :  

consider

String s1= "Santhosh" ;

String s2= "Santhosh" ; 

Console.WriteLine( ReferenceEquals(s1,s2)); // returns True, reason being dotnet runtime maintains an INTERN pool, contains  single reference to each unique string in the program .

Case 3 :  

consider

String s1= "Santhosh" ;

String s2= Console.ReadLine() 

Console.WriteLine( ReferenceEquals(s1,s2)); // returns False.

 Here .net runtime by default doesnt replace runtime input with shared reference . In order to check use 

string s2= String.Intern(Console.ReadLine() ); 

now the output will be true .