String interning

In computer science, string interning is a method of storing only one copy of each distinct string value, which must be immutable.[1] Interning strings makes some string processing tasks more time-efficient or space-efficient at the cost of requiring more time when the string is created or interned. The distinct values are stored in a string intern pool.

The single copy of each string is called its intern and is typically looked up by a method of the string class, for example String.intern()[2] in Java. All compile-time constant strings in Java are automatically interned using this method.[3]

String interning is supported by some modern object-oriented programming languages, including Java, Python, PHP (since 5.4), Lua[4] and .NET languages.[5] Lisp, Scheme, Julia, Ruby and Smalltalk are among the languages with a symbol type that are basically interned strings. The library of the Standard ML of New Jersey contains an atom type that does the same thing. Objective-C's selectors, which are mainly used as method names, are interned strings.

Objects other than strings can be interned. For example, in Java, when primitive values are boxed into a wrapper object, certain values (any boolean, any byte, any char from 0 to 127, and any short or int between −128 and 127) are interned, and any two boxing conversions of one of these values are guaranteed to result in the same object.[6]

History

Lisp introduced the notion of interned strings for its symbols. Historically, the data structure used as a string intern pool was called an oblist (when it was implemented as a linked list) or an obarray (when it was implemented as an array).

Modern Lisp dialects typically distinguish symbols from strings; interning a given string returns an existing symbol or creates a new one, whose name is that string. Symbols often have additional properties that strings do not (such as storage for associated values, or namespacing): the distinction is also useful to prevent accidentally comparing an interned string with a not-necessarily-interned string, which could lead to intermittent failures depending on usage patterns.

Motivation

String interning speeds up string comparisons, which are sometimes a performance bottleneck in applications (such as compilers and dynamic programming language runtimes) that rely heavily on associative arrays with string keys to look up the attributes and methods of an object. Without interning, comparing two distinct strings may involve examining every character of both.[Note 1] This is slow for several reasons: it is inherently O(n) in the length of the strings; it typically requires reads from several regions of memory, which take time; and the reads fill up the processor cache, meaning there is less cache available for other needs. With interned strings, a simple object identity test suffices after the original intern operation; this is typically implemented as a pointer equality test, normally just a single machine instruction with no memory reference at all.

String interning also reduces memory usage if there are many instances of the same string value; for instance, it is read from a network or from storage. Such strings may include magic numbers or network protocol information. For example, XML parsers may intern names of tags and attributes to save memory. Network transfer of objects over Java RMI serialization object streams can transfer strings that are interned more efficiently, as the String object's handle is used in place of duplicate objects upon serialization.[7]

Issues

Multithreading

If the interned strings are not immutable, one source of drawbacks is that string interning may be problematic when mixed with multithreading. In many systems, string interns are required to be global across all threads within an address space (or across any contexts which may share pointers), thus the intern pool(s) are global resources that should be synchronized for safe concurrent access. While this only affects string creation (where the intern pool must be checked and modified if necessary), and double-checked locking may be used on platforms where this is a safe optimization, the need for mutual exclusion when modifying the intern pool can be expensive.[8]

Contention can also be reduced by partitioning the string space into multiple pools, which can be synchronized independently of one another.

Reclaiming unused interned strings

Many implementations of interned strings do not attempt to reclaim (manually or otherwise) strings that are no longer used. For applications where the number of interned strings is small or fixed, or which are short-lived, the loss of system resources may be tolerable. But for long-running systems where large numbers of string interns are created at runtime, the need to reclaim unused interns may arise. This task can be handled by a garbage collector, though for this to work correctly weak references to string interns must be stored in the intern pool.

See also

Notes

  1. ^ The string comparison can halt at the first character mismatch. For strict equality, the lengths of the strings can also be compared before traversing the string: but finding the length of null-terminated strings does itself require traversing the string.

References

  1. ^ "String.Intern Method (String)". Microsoft Developer Network. Retrieved 25 March 2017.
  2. ^ String.intern()
  3. ^ "Chapter 15. Expressions". docs.oracle.com. Retrieved 30 January 2019.
  4. ^ "lua-users wiki: Immutable Objects". lua-users.org. Retrieved 30 January 2019.
  5. ^ rpetrusha. "String Class (System)". docs.microsoft.com. Retrieved 30 January 2019.
  6. ^ "Chapter 5. Conversions and Promotions". docs.oracle.com. Retrieved 30 January 2019.
  7. ^ "Java Object Serialization Specification: 1 - System Architecture". docs.oracle.com. Retrieved 30 January 2019.
  8. ^ "String.intern in Java 6, 7 and 8 - multithreaded access". java-performance.info. 3 September 2013. Retrieved 30 January 2019.

Read other articles:

Kewarganegaraan Swiss adalah sebuah status yang dipegang oleh seorang warga negara Swiss dan bisa didapatkan melalui kelahiran atau naturalisasi. Hukum Kewarganegaraan Swiss berdasarkan pada prinsip-prinsip berikut ini: Tiga tingkat kewarganegaraan (Konfederasi Swiss, kanton dan munisipalitas) Akuisisi kewarganegaraan melalui keturunan (jus sanguinis) Orang-orang yang tak bernegara Lihat pula Paspor Swiss Kartu identitas Swiss Bangsa Swiss Referensi Pranala luar Swiss nationality page of the ...

 

 

هذه المقالة يتيمة إذ تصل إليها مقالات أخرى قليلة جدًا. فضلًا، ساعد بإضافة وصلة إليها في مقالات متعلقة بها. (أبريل 2019) كالفين لوري معلومات شخصية الميلاد 13 فبراير 1983 (40 سنة)  فورت هود  مواطنة الولايات المتحدة  الطول 71 بوصة  الوزن 200 رطل  الحياة العملية المدرسة الأم جا

 

 

Artikel ini sebatang kara, artinya tidak ada artikel lain yang memiliki pranala balik ke halaman ini.Bantulah menambah pranala ke artikel ini dari artikel yang berhubungan atau coba peralatan pencari pranala.Tag ini diberikan pada Oktober 2022. Pantai Citra Informasi Lokasi Desa Sungai Cabang Barat, Kecamatan Pantai Lunci, Kabupaten Sukamara Negara Indonesia Koordinat 2°35′35″S 111°06′39″E / 2.59313°S 111.11082°E / -2.59313; 111.11082Koordinat: 2°35′35...

Puerto Salgar Municipio Iglesia de Puerto Salgar. BanderaEscudo Lema: ¡Construyendo Un Mejor Futuro Para Puerto Salgar! Puerto SalgarLocalización de Puerto Salgar en Colombia Puerto SalgarLocalización de Puerto Salgar en CundinamarcaCoordenadas 5°27′55″N 74°39′11″O / 5.4652777777778, -74.653055555556Entidad Municipio • País  Colombia • Departamento Cundinamarca • Provincia Bajo MagdalenaAlcalde Jaime Maldonado Mora (2020-2023)Eventos his...

 

 

Un mapa cultural del mundo elaborado por el World Values Survey, describiendo Estados Unidos como más alto en «valores tradicionales» y «valores de autoexpresión» en comparación con otros países. La sociedad de Estados Unidos tiene su base en la cultura occidental, y su origen es muy anterior a que Estados Unidos se convirtiese en un país independiente con rasgos propios en su música, arte, costumbres, cocina y folclore. Actualmente, Estados Unidos de América es un país étnica y ...

 

 

25-те співоче свято Есто́нське свя́то пі́сні (ест. üldlaulupidu) — загальнодержавне і національне співоче свято Естонії, де беруть участь різні хорові колективи і духові оркестри. Свято проводиться кожні п'ять років на території Талліннського Співочого поля. Організацією с...

Visegrád GroupKelompok VisegradKeanggotaan4 negara Eropa TengahPemimpin• Rotasi kepresidenan [1] Pendirian15 Februari 1991 Visegrád group logo Visegrád Group, atau disebut sebagai Visegrád Four atau V4, adalah aliansi dari empat negara Eropa Tengah – yaitu Republik Ceko, Hungaria, Polandia dan Slowakia – dengan tujuan kerjasama dan lebih memperkokoh integrasi di dalam Eropa. Nama kelompok ini dalam bahasa keempat negara itu adalah Visegrádská čtyřka atau V...

 

 

Đối với các định nghĩa khác, xem Giờ chuẩn miền Đông (định hướng) và Giờ ánh sáng ngày miền Đông (định hướng).   EDT tương ứng UTC−4 Múi giờ miền Đông (ET) của Tây Bán Cầu rơi vào phần lớn các vùng dọc theo duyên hải phía đông của Bắc Mỹ và duyên hải phía tây của Nam Mỹ. Múi giờ miền Đông là giờ tính bằng cách lấy Giờ phối hợp quốc tế (UTC) trừ đi 5 tiếng và d...

 

 

Puerto Princesa Highly Urbanized City اللقب The City in the Forest الاسم الرسمي (بالإنجليزية: City of Puerto Princesa)‏  Map of Palawan showing the location of Puerto Princesa الإحداثيات 09°44′N 118°44′E / 9.733°N 118.733°E / 9.733; 118.733 تأسس 1872 Cityhood June 21, 1961 تقسيم إداري  بلد  Philippines  مناطق الفلبين ميماروبا (Region IV-B)  مقاطعة في ا...

2011 South Korean television drama series Glory JanePromotional posterAlso known asMan of Honor Young-kwang's Jae-in The Glory of Jae-in Young Love JaneGenreRomanceMelodramaActionSportsWritten byKang Eun-kyungDirected byLee Jung-subStarringChun Jung-myungPark Min-youngLee Jang-wooOpening themeGlory Jane (Title)Country of originSouth KoreaOriginal languageKoreanNo. of episodes24ProductionProduction locationKoreaRunning time60 minutes Wednesdays and Thursdays at 21:55 (KST)Production companyKim...

 

 

李學周男演员本名李學周原文名이학주罗马拼音Lee Hak Joo国籍 韩国出生 (1989-01-09) 1989年1月9日(34歲) 韩国韓國职业演員语言韓語教育程度漢陽大學戲劇電影系學士配偶圈外女性(2022年结婚)亲属父母、妹妹出道日期2012年出道作品電影《飯糰》代表作品《第12名輔助司祭(朝鲜语:12번째 보조사제)》《Oh 我的鬼神君》《夫妻的世界》活跃年代2012年至今经纪公司SM C&a...

 

 

دار الحفيرة (محلة) تقسيم إداري البلد  اليمن المحافظة محافظة إب المديرية مديرية حبيش العزلة عزلة صائر القرية قرية العرض السكان التعداد السكاني 2004 السكان 78   • الذكور 28   • الإناث 50   • عدد الأسر 14   • عدد المساكن 13 معلومات أخرى التوقيت توقيت اليمن (+3 غرينيتش) تعدي...

American basketball player (1941–2016) Nate ThurmondThurmond with the Warriors in 1969Personal informationBorn(1941-07-25)July 25, 1941Akron, Ohio, U.S.DiedJuly 16, 2016(2016-07-16) (aged 74)San Francisco, California, U.S.Listed height6 ft 11 in (2.11 m)Listed weight225 lb (102 kg)Career informationHigh schoolCentral (Akron, Ohio)CollegeBowling Green (1960–1963)NBA draft1963: 1st round, 3rd overall pickSelected by the San Francisco WarriorsPlaying career1963...

 

 

Series of global conferences Oslo Freedom ForumFrom the press conference of the 2018 Oslo Freedom Forum.Founded2009 (Oslo, Norway)Patron(s)Peter ThielOrganised byHuman Rights FoundationWebsitewww.oslofreedomforum.com Oslo Freedom Forum (OFF) is a series of global conferences run by the New York–based non-profit Human Rights Foundation under the slogan Challenging Power.[1] OFF was founded in 2009 as a one-time event and has taken place annually ever since. The forum aims to bring to...

 

 

This article is about American-style cheerleading. For Japanese-style cheerleading, see Ōendan. Cheerleader redirects here. For other uses, see Cheerleader (disambiguation). Athletic activity based on cheering for a team This article includes a list of general references, but it lacks sufficient corresponding inline citations. Please help to improve this article by introducing more precise citations. (December 2020) (Learn how and when to remove this template message) College cheerleaders pe...

Norwegian folk-pop duo Kings of ConvenienceKings of Convenience performing in 2016Background informationOriginBergen, NorwayGenresBossa nova, Indie pop, indie folk[1]Years active1999–presentLabelsEMI, Astralwerks, KindercoreMembers Erlend Øye Eirik Glambek Bøe Websitekingsofconvenience.eu Kings of Convenience is an indie folk-pop duo from Bergen, Norway, consisting of Erlend Øye and Eirik Glambek Bøe. History Øye and Bøe were both born in 1975 (Øye on 21 November and Bøe on ...

 

 

In this Chinese name, the family name is Chan. Chan ShenChan ShenBornChan Yi-Cheng(1940-03-11)11 March 1940Taichung, TaiwanDied26 April 1984(1984-04-26) (aged 44)Hong KongOccupationactorYears active1971—1984Chinese nameTraditional Chinese詹森Transcriptions Chan Shen (11 March 1940 - 26 April 1984) was a Taiwanese-born Hong Kong film actor. He is best known for his roles as gangsters or villains in Hong Kong action cinema in the 1970s. Already an established film actor in Ta...

 

 

هذه المقالة يتيمة إذ تصل إليها مقالات أخرى قليلة جدًا. فضلًا، ساعد بإضافة وصلة إليها في مقالات متعلقة بها. (أبريل 2023) فرسان النور Knights of Light المطور استديو رامبلنج للالعاب الناشر استديو رامبلنج للالعاب الموزع ستيم  محرك اللعبة أنريل إنجن النظام مايكروسوفت ويندوز تاریخ الإ...

American film director Gregg ArakiAraki in 2014Born (1959-12-17) December 17, 1959 (age 63)Los Angeles, California, U.S.EducationUniversity of California, Santa Barbara (B.A.)University of Southern California (M.F.A.)Occupation(s)Film director, screenwriter, producerYears active1987–presentStyleNew Queer Cinema Gregg Araki (born December 17, 1959) is an American filmmaker. He is noted for his heavy involvement with the New Queer Cinema movement. His film Kaboom (2010) was the firs...

 

 

A latte stone in Latte Stone Park, Hagåtña, Guam A latte stone, or simply latte (also latde, latti, or latdi), is a pillar (Chamorro language: haligi) capped by a hemispherical stone capital (tasa) with the flat side facing up. Used as building supports by the ancient Chamorro people, they are found throughout most of the Mariana Islands. In modern times, the latte stone is seen as a sign of Chamorro identity and is used in many different contexts. Construction Reconstruction of latte stone...

 

 

Strategi Solo vs Squad di Free Fire: Cara Menang Mudah!