Reducing string memory usage with the Intern method

Reducing string memory usage with the Intern method

A .NET application can optimize string management by maintaining an internal pool of string values known as intern pool. If the value being assigned to a string variable coincides with one of the strings already in the intern pool, no additional memory is created and the variable receives the address of the string value in the pool. The compiler is capable of using the intern pool to optimize string initialization, and have two string variables pointing to the same String object in memory, which of course helps saving memory. This optimization step isn’t performed at run time though, because the search in the pool takes time and in most cases it would fail, adding overhead to the application without bringing any benefit.

' Prove that no optimization is performed at run time.s1 = "1234" s1 &= "5678"s2 = "12345678"' These two variables point to different String objects.Console.WriteLine(s1 Is s2)                     ' => False

You can optimize string management by using the Intern shared method. This method searches a string value in the intern pool and returns a reference to the pool element that contains the value if the value is already in the pool. If the search fails, the string is added to the pool and a reference to it is returned. See how you can “manually” optimize the preceding code snippet by using the String.Intern method:

s1 = "ABCD" s1 &= "EFGH"' Move S1 to the intern pools1 = String.Intern(s1)' Assign S2 a string constant (that we know is in the pool).s2 = String.Intern("ABCDEFGH")' These two variables point to the same String object.Console.WriteLine(s1 Is s2)                     ' => True

This optimization technique makes sense only if you’re working with long strings and if you’re working with strings that appear in multiple portions of the applications. Another good time to use this technique is when you have many instances of a server-side component that contain similar string variables, such as a database connection string. Even if these strings don’t change during the program’s lifetime, they’re usually read from a file, and therefore the compiler can’t optimize their memory allocation automatically. Using the Intern method, you can help you application produce a smaller memory footprint.

Share the Post:
data observability

Data Observability Explained

Data is the lifeblood of any successful business, as it is the driving force behind critical decision-making, insight generation, and strategic development. However, due to its intricate nature, ensuring the

Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular