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.

See also  How to Create and Deploy QR Codes Online: A Comprehensive Guide

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist