Bob On Development

Musings on the craft and business of software development









May 19, 2007

Optimize Memory Consumption Using String Interning

Filed under: — bob @ 3:39 pm

There are situations where an application needs to load large collections of strings or types that contain a lot of string references. By default, any two strings in memory are unique objects, even though an equality comparison shows they have the same values. This is a side effect of the immutable character of strings in .NET (and in Java). It isn’t always desirable.

Suppose you need to add a thousand hypothetical Person objects to a collection. These objects include a person’s name and address information. Let us further suppose that these Persons all live in the United States. Worst case, there are just over 50 possible state codes (the 50 states plus territories and the District of Columbia and possibly military addresses). Wouldn’t it be nice not to have hundreds of copies of each unique state code in memory?

This is where an often overlooked technique called string interning comes into play. Each .NET assembly has an intern pool, which is in essence a collection of unique strings. When your code is compiled, all the string literals you reference in your code are added to this pool. Since many literals in a program tend to appear in multiple places, this conserves memory. A simplistic example:

if (bar == "FOO") {
  // do something here
} else if (foo == "FOO") {
  // do something here
} else if (fooBar = "FOO") {
  // do something here
}

In the above example, “FOO” is added to the intern pool at compile time, so there is one copy of “FOO” rather than three. This saves memory.

For performance reasons I’ll go into shortly, interning is not normally applied to runtime string values, but at times it makes sense to do so. In our collection of Persons, let’s say we load each Person from a DataReader. We can intern the states as we load them, like so:

personInstance.State = String.Intern(drPerson["state"].ToString());

If for example the state code is “AZ”, String.Intern() looks to see if “AZ” is already in the intern pool. If it is, a reference to the interned string is returned. Otherwise, a new “AZ” string is created and that reference is added to the intern pool. If you end up with 1,200 persons in Arizona, you will have one “AZ” instance instead of 1,200 of them — a tremendous memory savings.

Depending on the typical distribution of unique values, the city might also be useful to intern. Basically, any time you have an attribute with a limited number of values that will be assigned to a large number of entities, string interning might be worth considering. This is even truer for long strings.

Of course, any time you optimize for one thing, you de-optimize for one or more other things, and interning is no exception.

The first down side is performance. String.Intern() must search the intern pool, and this is extra overhead compared to a string assignment. I have not formally benchmarked it, but it’s substantial enough that it has a noticeable subjective impact on performance in many cases. So you’ll want to avoid interning techniques when you absolutely need blistering performance. In the situations I actually used it, adequate performance was acceptable, and interning allowed us to avoid unacceptably low system capacities. Besides, many alternatives to an entirely in-memory solution can put just as big a damper on performance.

The second downside is persistence. There is no way to remove string references from the intern pool, and the memory used by the intern pool is not likely to be released until the CLR itself exits. You heard that right: the intern pool and its memory usage will probably outlive your application’s execution and even the termination of your app domain. For purposes of managing string literals, this isn’t a practical problem. But if you are going to load zillions of additional unique values to the intern pool in a system with constant uptime (such as a process called from a Windows service) then you may use up enough memory to begin to impact overall performance of all CLR applications.

A final, more minor issue, is that to intern a string you still have to create it. A String.Intern() call momentarily creates a string and then searches the intern pool. If the value already is in the pool, then the string reference goes out of scope and the released memory is eventually garbage-collected, but the overhead of string creation is not eliminated with String.Intern().

Despite these downsides, string interning, judiciously applied, can be a real life saver. Returning to my (simplistic) example above, you wouldn’t ordinarily apply this technique to state or region codes because in most applications you will not (and probably should not) load a large number of persons into a memory structure at one time anyway. There is usually no point in the added complexity and performance hit just to save a few kilobytes.

But the technique shines in bulk data processing applications, such as making iterative scrubbing passes over raw data from external sources before persisting it to a database. You might use a DataTable or a custom collection of your own to load arbitrary data in memory and then filter and transform it in various ways, entirely in memory, before committing it to some permanent data store. You might be seeking overall performance and / or simplicity by keeping everything in memory. Applying interning to certain columns could greatly increase the capacity of such a system.

Basically, the larger the strings, and the fewer the possible number of unique values, the more memory saved per DataRow or other collection item. Your mileage may vary, but string interning is a good tool in certain situations.

There is another win with interned strings. When you know that two strings are interned, you can make a super-fast string comparison this way:

if (object.ReferenceEquals(oneInternedString,anotherInternedString)) {}

Or, remembering that all string literals are interned, this more common scenario also works:

if (object.ReferenceEquals(anInternedString,"FOO") {}

Again, this only makes sense if you have thousands of comparisons to do, of course — and you have to know at coding time that the two strings are both interned.

Update: It occurs to me that here lies the seeds of a near-perfect general usage for interning that should be high benefits / low risk. Any time you have a set of known possible string values that you need to compare against and take action on, you are going to have if / else or switch /case statements testing for those known string literals, so they will be in the intern pool anyway. Therefore, you might as well intern any runtime strings that will be members of that same set of values and use the above object.ReferenceEquals() optimization with them. You get a great performance benefit and you aren’t adding anything new to the intern pool at runtime. Again, this isn’t worth bothering with for a set of tests executed once but in many interative situations it could be well worth it.

1 Comment »

  1. thank you for this interesting info.
    didnt know the Intern() method

    Comment by Petz — January 23, 2008 @ 9:04 am

RSS feed for comments on this post. TrackBack URI

Leave a comment

Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

(required)

(required)


Powered by WordPress

Augmentin Avandamet Rhinocort Elavil Gasex Glucotrol XL Zelnorm Vermox Penis Growth Oil Nymphomax Adalat Prograf Geriforte Medithin Avalide Lariam Viagra Erexor Sarafem Confido Himplasia Arimidex Fosamax ActoPlus Met Mentat Cardizem Hytrin Cafergot Lasuna Mycelex G Hyzaar Buy Pro Erex Buy Lincocin Buy Viramune Buy Micardis Buy Nymphomax Buy Omnicef Buy Effexor Buy Accutane Buy Levothroid Buy Cialis Jelly Buy Femcare Buy Amoxil Buy Aleve Buy Cephalexin Buy Lotrisone Buy Acticin Buy Touch Up Kit Buy Metabo UltraMax Buy Orgasm Enhancer Buy Penis Growth Pack Buy Levlen Buy Styplon Buy Aceon Cheap Loxitane Cheap Differin Cheap Geriforte Cheap Dramamine Cheap Sinequan Cheap Hoodia Cheap Nolvadex Cheap Womens Intimacy Enhancer Cheap Medithin Cheap Female Sexual Tonic Cheap Purinethol Cheap Inderal Cheap Flomax Cheap Orgasm Enhancer Cheap Zimulti Cheap Erexor Cheap Avandamet Cheap Ceftin Cheap Buspar Cheap ZMA Power Cheap Wellbutrin SR Cheap Hoodia Gordonii HG p57 Cheap Singulair Cheap Avandia Cheap Soma Credit reporting system For low credit scores Commercial credit report Understanding credit score Credit report and Florida free credit report Chase credit card status 3 credit reporting agencies Beacon credit score Federal credit reporting act To credit reporting agencies Fix your credit report On line credit card applications Credit card offers Card credit reward travel Credit score formula Credit reports from all Credit free instant report Annual report credit Order credit reports Instant personal credit report Credit beacon score Juniper credit card application Free instant credit reports Airline credit card miles National credit card debt Vue prepaid credit card Credit card debt calculator Chase credit card complaints Is credit score Elan credit card services Balance transfer credit cards Fix my credit score Credit card machines uk Check credit report fix Credit scores of Credit report uk Balance transfers credit cards Average credit score Increasing credit scores Is my credit score Business credit report Redit card pros cons Acceptable credit score Credit card business industrial Credit reports for Fast credit score increase Credit card debt facts On line credit report Free credit reporting Order credit report Chase credit card application Credit reporting act litigation Credit report consumer Clean up credit report Affect your credit score Credit report annual Credit report online Chase redit card Getting a credit score Credit card debt history Credit score after bankruptcy Credit scores meaning Stop credit card offer Ranked credit card offers Mobile credit card processing Linkpoint credit card machine Credit card applications in Credit report disputes Student credit card debt Credit reporting columbia house Credit report service Cheap credit card uk 0 credit card offer Credit report agencies Credit report score understanding Credit cards 0 apr Anual credit report Application aspen card credit Credit score higher Credit card debt management Citibank credit card offers Great credit card offer Free business credit reports Introductory offer credit card Money bank credit card Interpreting credit scores Get credit reports Free credit report Credit card apply online Credit score services Interest credit card offers Credit card debt eliminate Equifax credit reporting Instant credit card offer Credit card consolidation loans Bad credit score Credit card application uk Credit rating score scale Free credit score Experian credit report Credit report.com Article credit card debt Consolidation credit card debt Credit card consolidation uk Stopping credit card offer Read my credit report Obtain a credit report Mint credit card deal Raise my credit score Experian credit report uk Reports credit cards Hurt my credit score Discover credit card offer Good credit rating score Of my credit report Repairing credit score Credit reporting codes Credit reports on Hsbc credit card Credit card application online Repair my credit report Apr credit card offers Credit card debt advice Credit scores by Compare credit card offers Prepaid credit card companies Credit card debt laws Unlimited credit reports Annual credit report request Get my credit report Aarp chase credit card Card consolidation credit debt Credit report companies About credit scores Card credit debt free Transunion credit score Free credit card report Application card citi credit Corporate credit card application Credit scores work Consumer credit reports Credit scores mortgage Freecredit report Credit reporting service Credit card application with Credit scores and Personal credit report canada Credit report identity theft Free anual credit report Improving credit score Credit score uk My annual credit report Landlord credit report Credit score rates With a credit score Credit report government The credit reporting Up credit reports Instant credit reports Fre credit report Visa card bad credit Fair credit reporting act Freecreditreports Credit report repair service Free online credit report To increase credit score Bank one credit card American credit card debt Credit fix repair report Stop credit card debt Instant credit reports uk Low credit scores Colorado free credit report Free transunion credit report Of credit score Company credit report Credit reports with Personal credit score repair Credit scores only Obtain free credit score Cic credit report Eliminate credit card debt Free yearly credit reports The best credit score Credit report canada Wamu secured credit card Uk credit card debt Hsbc rs credit card Check credit report equifax Providian credit card company Secured credit or card Canada credit report Online Femcare Lipitor Muscle Pain Hydrocodone No Prescription Online Furosemide Online Inderal Online Maximum Lipotropics Online Viagra Soft Tabs Online Rythmol SR Levitra Actress Online Avalide Online Lynoral Online Neurontin Online Cardura Online Valtrex Online Fosamax Online Ditropan Online Diamox Online MetaboSafe Online Anafranil Online Viramune Online Advair Diskus Online Pro Erex Online Medrol Online Levaquin Online Echinacea Online Betnovate Online Prevacid Online Male Enhancement Oil Online Vasodilan Online Glucotrol XL Lorazepam Online Cymbalta Online Endep Online Confido Online Keftab Online Depakote Lortab Online Prozac Online Methox 400 Online Anabol AMP Online Tribulus Lipitor Side Affects Online Bentyl Online Dramamine Online Geodon Xanax Addiction Vicodine Online Indocin Online Trimox Online Shoot Carisoprodol 350 Mg Vicodin Hp Online Colostrum 800 Tramadol Cod Zoloft Withdrawal Online Cardizem Online Hangover Helper Online Isoptin Online Nolvadex Online Amaryl Online Penisole Cialis Dosage Phentermine No Prescription Vicodin Lorazepam Overdose Online Liponexol Online Sumycin Online Evecare Online Differin Online Urispas Online Biaxin Online Antabuse Online Ventolin Online Styplon Carisoprodol Soma Online Sustiva Online Prinivil Online Casodex Online Vermox Diazepam Online Cafergot Online Detrol Online Melatonin Zoloft Side Effects Online Trandate Online Reglan Xanax Dosage Lorazepam Addiction Online Avapro Adipex P Didrex Diet Pills Cialis.Com Ultram Online Calcium Carbonate Online Zyloprim Online Desyrel Online Ponstel Viagra Side Effects Xanax Withdrawal Viagra Alternatives Online GABA (HGH Booster) Online Probalan Viagra Dosage Online Orgasm Enhancer Hydrocodone Apap Online Flexisyn Adipex No Prescription Xanax Abuse Viagra Online Tofranil Propecia Generic Phentermine Online Online Mentat Online Zanaflex Online Noxide Online Loxitane Online Lukol Levitra Drug Online Extendaquin Alprazolam No Prescription Online Hyzaar Online Pletal Online Zovirax Online Cialis Soft Tabs Online Relafen Online Quibron T Online Paxil Online Rocaltrol Online Coreg Online Mevacor Carisoprodol Online Maxaquin Online Tenormin Online Remeron Online Evegen Online Claritin Ativan Drug Online QuickBust Diazepam Dosage Tramadol Hcl Online Cystone Online Nymphomax