In a language such as java/c#, which is based on reference semantics, a string that exists as an immutable object can be reused by some mechanism if the content is the same. Because for such a language, a string that points to two memory locations in memory with the same contents is no different from pointing to a string at the same time. Especially for a large number of XML files using string parsing similar occasions, such optimization can greatly reduce the memory footprint of the program, such as the SAX parsing engine standard specifically defined a http://xml.org/sax/features/string-interning Attributes are used for string reuse.
At the language level, java/c# directly provides string.intern support. For Java, the implementation is very similar. By the String.intern method, the current string is keyed with the content, and the object reference is a value and placed in a global hash table.
Code:
//
//Java/lang/string.java
//
Public final class String
{
//...
Public native String intern ()//Use JNI function implementation for efficiency
//
//Hotspot/src/share/vm/prims/jvm.cpp
//
Jvm_entry (jstring, jvm_internstring (jnienv *env, jstring str))
Jvmwrapper ("jvm_internstring");
if (str = NULL ) return NULL;
Oop string = Jnihandles::resolve_non_null (str);//resolve reference to internal handle
OOP result = Stringtable::intern (string, Check_ 0); Perform the actual string intern action
Return (jstring) jnihandles::make_local (env, result);//Get references to internal handles
Jvm_end
//
Hotspot/src/share/vm/memory/symboltable.cpp
//
Oop Stringtable::intern (OOP string, traps)
{
if (string = = null) return null;
Resourcemark rm (thread);//Protect thread resource area
int length;
Handle h_string (THREAD, String);
jchar* chars = java_lang_string::as_unicode_string (string, length);//Get actual string content
Oop result = Intern (H_stri Ng, chars, length, CHECK_0); Complete the string intern action
return result;
Oop Stringtable::intern (Handle string_or_null, jchar* name, int len, traps)
{
int hashvalue = Hash_st Ring (name, Len); First computes the hash value based on the string contents
stringtablebucket* bucket = bucketfor (HashValue); Ookup (name, Len); It then detects if the string already exists
//Found
if (string!= NULL) return string,
Otherwise, add to symbol to table
return Basic_add (string_or_null, name, Len, HashValue, check_0);//Insert a string into a hash table br>}