SlideShare ist ein Scribd-Unternehmen logo
1 von 128
Downloaden Sie, um offline zu lesen
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Was jeder Java-Entwickler ¨uber
Strings wissen sollte
Bernd M¨uller
19.4.2016
Bernd M¨uller 19.4.2016 1/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Vor vielen, vielen Jahren . . .
Vor vielen, vielen Jahren . . .
Bernd M¨uller 19.4.2016 2/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Vor vielen, vielen Jahren . . .
Vor vielen, vielen Jahren . . .
public class HelloWorld {
public static void main(String [] args) {
System.out.println("Hello World");
}
}
Bernd M¨uller 19.4.2016 3/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Vor vielen, vielen Jahren . . .
Vor vielen, vielen Jahren . . .
public class HelloWorld {
public static void main(String [] args) {
System.out.println("Hello World");
}
}
Was ist
”
String[]“ ?
Was ist
”
”Hello World”“ ?
Hat das irgend etwas
miteinander zu tun ?
Bernd M¨uller 19.4.2016 3/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Referent
Vorstellung Referent
Prof. Informatik (Ostfalia, HS Braunschweig/Wolfenb¨uttel)
Buchautor (JSF, Seam, JPA, ...)
Mitglied EGs JSR 344 (JSF 2.2) und JSR 338 (JPA 2.1)
Gesch¨aftsf¨uhrer PMST GmbH
. . .
Bernd M¨uller 19.4.2016 4/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Motivation
Motivation
Bernd M¨uller 19.4.2016 5/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Motivation
Bernd M¨uller 19.4.2016 6/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Motivation


¨
©
Bernd M¨uller 19.4.2016 7/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Motivation
Auszug aus Abschnitt String Interning
”
Strings are, far and away, the most common Java
object; your application’s heap is almost certainly filled
with them.“
Bernd M¨uller 19.4.2016 8/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Motivation
Bernd M¨uller 19.4.2016 9/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Motivation
9
8
6
7
Bernd M¨uller 19.4.2016 10/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Motivation
Bernd M¨uller 19.4.2016 11/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Motivation
9
8
6
7
Bernd M¨uller 19.4.2016 12/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
String-Klassen
String-Klassen und -Methoden
Bernd M¨uller 19.4.2016 13/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
String-Klassen
Klassen mit String-Bezug: die ¨ublichen Verd¨achtigen
java.lang.String, seit Java 1.0
The String class represents character strings.
java.lang.StringBuffer, seit Java 1.0
A thread-safe, mutable sequence of characters.
java.lang.StringBuilder, seit Java 5
A mutable sequence of characters.
java.util.StringTokenizer, seit Java 1.0
The string tokenizer class allows an application to break a
string into tokens.
java.util.StringJoiner, seit Java 8
StringJoiner is used to construct a sequence of characters
separated by a delimiter . . .
Bernd M¨uller 19.4.2016 14/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
String-Klassen
Klassen mit String-Bezug: die ¨ublichen Verd¨achtigen
java.lang.String, seit Java 1.0
The String class represents character strings.
java.lang.StringBuffer, seit Java 1.0
A thread-safe, mutable sequence of characters.
java.lang.StringBuilder, seit Java 5
A mutable sequence of characters.
java.util.StringTokenizer, seit Java 1.0
The string tokenizer class allows an application to break a
string into tokens.
java.util.StringJoiner, seit Java 8
StringJoiner is used to construct a sequence of characters
separated by a delimiter . . .
Bernd M¨uller 19.4.2016 14/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
String-Klassen
Klassen mit String-Bezug: die ¨ublichen Verd¨achtigen
java.lang.String, seit Java 1.0
The String class represents character strings.
java.lang.StringBuffer, seit Java 1.0
A thread-safe, mutable sequence of characters.
java.lang.StringBuilder, seit Java 5
A mutable sequence of characters.
java.util.StringTokenizer, seit Java 1.0
The string tokenizer class allows an application to break a
string into tokens.
java.util.StringJoiner, seit Java 8
StringJoiner is used to construct a sequence of characters
separated by a delimiter . . .
Bernd M¨uller 19.4.2016 14/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
String-Klassen
Klassen mit String-Bezug: die ¨ublichen Verd¨achtigen
java.lang.String, seit Java 1.0
The String class represents character strings.
java.lang.StringBuffer, seit Java 1.0
A thread-safe, mutable sequence of characters.
java.lang.StringBuilder, seit Java 5
A mutable sequence of characters.
java.util.StringTokenizer, seit Java 1.0
The string tokenizer class allows an application to break a
string into tokens.
java.util.StringJoiner, seit Java 8
StringJoiner is used to construct a sequence of characters
separated by a delimiter . . .
Bernd M¨uller 19.4.2016 14/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
String-Klassen
Klassen mit String-Bezug: die ¨ublichen Verd¨achtigen
java.lang.String, seit Java 1.0
The String class represents character strings.
java.lang.StringBuffer, seit Java 1.0
A thread-safe, mutable sequence of characters.
java.lang.StringBuilder, seit Java 5
A mutable sequence of characters.
java.util.StringTokenizer, seit Java 1.0
The string tokenizer class allows an application to break a
string into tokens.
java.util.StringJoiner, seit Java 8
StringJoiner is used to construct a sequence of characters
separated by a delimiter . . .
Bernd M¨uller 19.4.2016 14/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
String-Klassen
Padding
Padding in der Regel mit Apache Commons-Lang
StringUtils: leftPad(), rightPad()
Bernd M¨uller 19.4.2016 15/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
String-Klassen
Padding
Padding in der Regel mit Apache Commons-Lang
StringUtils: leftPad(), rightPad()
Man ben¨otigt aber keine Bibliothek, ist im SDK eingebaut
Schl¨ussel: java.util.Formatter als printf-Nachahmung
Bernd M¨uller 19.4.2016 15/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
String-Klassen
Padding
Padding in der Regel mit Apache Commons-Lang
StringUtils: leftPad(), rightPad()
Man ben¨otigt aber keine Bibliothek, ist im SDK eingebaut
Schl¨ussel: java.util.Formatter als printf-Nachahmung
Beispiel:
String.format(%1 $10s, hello)
String.format(%1$-10s, hello)
Bernd M¨uller 19.4.2016 15/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Character-Codierungen
Character-Codierungen
Bernd M¨uller 19.4.2016 16/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Character-Codierungen
Character-Codierungen
Historisch Java mit 16 Bit codiertem char-Datentyp
Bernd M¨uller 19.4.2016 17/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Character-Codierungen
Character-Codierungen
Historisch Java mit 16 Bit codiertem char-Datentyp
Mit Java 5 wurde Unicode 4.0 als Character-Codierung
eingef¨uhrt [CHAR1]
Bernd M¨uller 19.4.2016 17/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Character-Codierungen
Character-Codierungen
Historisch Java mit 16 Bit codiertem char-Datentyp
Mit Java 5 wurde Unicode 4.0 als Character-Codierung
eingef¨uhrt [CHAR1]
Damit Codierungen mit mehr als 16 Bit m¨oglich, die als
sogenannte Surrogate repr¨asentiert werden
Bernd M¨uller 19.4.2016 17/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Character-Codierungen
Java Tutorial: Supplementary Characters as Surrogates
”
To support supplementary characters without changing the char
primitive data type and causing incompatibility with previous Java
programs, supplementary characters are defined by a pair of code
point values that are called surrogates. The first code point is from
the high surrogates range of U+D800 to U+DFBB, and the
second code point is from the low surrogates range of U+DC00 to
U+DFFF. For example, the Deseret character LONG I, U+10400,
is defined with this pair of surrogate values: U+D801 and
U+DC00.“ [CHAR2]
Bernd M¨uller 19.4.2016 18/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Character-Codierungen
Character-Codierungen (cont’d)
Beschreibung in Java-Doc java.lang.Character [CHAR4]
Bernd M¨uller 19.4.2016 19/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Character-Codierungen
Character-Codierungen (cont’d)
Beschreibung in Java-Doc java.lang.Character [CHAR4]
¨Uberblick
Java 1.4: Unicode 3.0
Java 5: Unicode 4.0
Java 6: Unicode 4.0
Java 7: Unicode 6.0.0
Java 8: Unicode 6.2.0
Java 9: Unicode 8.0.0
Bernd M¨uller 19.4.2016 19/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Character-Codierungen
Character-Codierungen (cont’d)
Beschreibung in Java-Doc java.lang.Character [CHAR4]
¨Uberblick
Java 1.4: Unicode 3.0
Java 5: Unicode 4.0
Java 6: Unicode 4.0
Java 7: Unicode 6.0.0
Java 8: Unicode 6.2.0
Java 9: Unicode 8.0.0
Basic Encodings in lib/rt.jar, Extended Encodings in
lib/charsets.jar, Dokumentation in [CHAR3]
Bernd M¨uller 19.4.2016 19/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Performanz
Performanz
Bernd M¨uller 19.4.2016 20/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Performanz
Performanz: toString()
Performanz: toString()
Bernd M¨uller 19.4.2016 21/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Performanz
Performanz: toString()
Who Cares About toString Performance ?
Blog von Antonio Goncalves [Gonc]
Bernd M¨uller 19.4.2016 22/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Performanz
Performanz: toString()
Who Cares About toString Performance ?
Blog von Antonio Goncalves [Gonc]
Use Case: Großer Batch mit Logging und toString(), o.¨a.
Bernd M¨uller 19.4.2016 22/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Performanz
Performanz: toString()
Who Cares About toString Performance ?
Blog von Antonio Goncalves [Gonc]
Use Case: Großer Batch mit Logging und toString(), o.¨a.
Effective Java [Joshua Bloch]
Item 10: Always override toString
Bernd M¨uller 19.4.2016 22/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Performanz
Performanz: toString()
Who Cares About toString Performance ?
Blog von Antonio Goncalves [Gonc]
Use Case: Großer Batch mit Logging und toString(), o.¨a.
Effective Java [Joshua Bloch]
Item 10: Always override toString
toString()-Methode durch IDE generiert oder selbst
gemacht mit Alternativen
Bernd M¨uller 19.4.2016 22/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Performanz
Performanz: toString()
Who Cares About toString Performance ?
Blog von Antonio Goncalves [Gonc]
Use Case: Großer Batch mit Logging und toString(), o.¨a.
Effective Java [Joshua Bloch]
Item 10: Always override toString
toString()-Methode durch IDE generiert oder selbst
gemacht mit Alternativen
Null-Checks nicht vergessen
Bernd M¨uller 19.4.2016 22/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Performanz
Performanz: toString()
Who Cares About toString Performance ?
Blog von Antonio Goncalves [Gonc]
Use Case: Großer Batch mit Logging und toString(), o.¨a.
Effective Java [Joshua Bloch]
Item 10: Always override toString
toString()-Methode durch IDE generiert oder selbst
gemacht mit Alternativen
Null-Checks nicht vergessen
Untersucht: JDK, Guava, CommonsLang3
Bernd M¨uller 19.4.2016 22/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Performanz
Performanz: toString()
Who Cares About toString Performance ?
Blog von Antonio Goncalves [Gonc]
Use Case: Großer Batch mit Logging und toString(), o.¨a.
Effective Java [Joshua Bloch]
Item 10: Always override toString
toString()-Methode durch IDE generiert oder selbst
gemacht mit Alternativen
Null-Checks nicht vergessen
Untersucht: JDK, Guava, CommonsLang3
Gemessen:
”
Average performance with Java
Microbenchmarking Harness (ops/s)“
Bernd M¨uller 19.4.2016 22/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Performanz
Performanz: toString()
Who Cares About toString Performance ? (cont’d)
Ergebnisse
Technic Average ops/s
String concat with + 142.075,167
String builder 141.463,438
Objects.toString 140.791,365
Guava 110.111,808
ToStringBuilder (append) 75.165,552
ToStringBuilder (reflectionToString) 34.930,630
ReflectionToStringBuilder 23.204,479
Bernd M¨uller 19.4.2016 23/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Performanz
Performanz: toString()
Who Cares About toString Performance? (cont’d)
Zusammenfassung:
”
Today with the JVM optimisation, we can safely use
the + symbol to concatenate Strings (and use
Objects.toString to handle nulls). With the utility class
Objects that is built-in the JDK, no need to have external
frameworks to deal with null values. So, out of the box,
the JDK has better performance than any other technic
described in this article.“ [Antonio Goncalves, Gonc]
Bernd M¨uller 19.4.2016 24/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Performanz
Performanz: toString()
Who Cares About toString Performance? (cont’d)
Zusammenfassung:
”
Today with the JVM optimisation, we can safely use
the + symbol to concatenate Strings (and use
Objects.toString to handle nulls). With the utility class
Objects that is built-in the JDK, no need to have external
frameworks to deal with null values. So, out of the box,
the JDK has better performance than any other technic
described in this article.“ [Antonio Goncalves, Gonc]
Nachtrag: sowieso nur interessant, wenn Sie toString() sehr oft
aufrufen
Bernd M¨uller 19.4.2016 24/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Performanz
Performanz: String-Konkatenation
Performanz: String-Konkatenation
Bernd M¨uller 19.4.2016 25/60
JDK String-Konkatenation
@Benchmark
// String +
public static String concat () {
String result = ;
for (int i = 0; i  IT; i++) {
result += i;
}
return result;
}
@Benchmark
// StringBuffer
public static String concat () {
StringBuffer builder = new Stri
for (int i = 0; i  IT; i++) {
builder.append(i);
}
return builder.toString ();
}
@Benchmark
// Joining Collector
public static String concat () {
return IntStream.range (0, IT)
.mapToObj(String :: valueOf)
.collect(Collectors.joining ());
}
@Benchmark
// StringBuilder
public static String concat () {
StringBuilder builder = new Str
for (int i = 0; i  IT; i++) {
builder.append(i);
}
return builder.toString ();
}
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Performanz
Performanz: String-Konkatenation
JMH Ergebnisse
Benchmark Score Error Units
SC.concatWithJoiningCollector 2898,767 ± 5,378 ops/s
SC.concatWithString 25,434 ± 0,059 ops/s
SC.concatWithStringBuffer 5375,578 ± 39,959 ops/s
SC.concatWithStringBuilder 6030,804 ± 13,088 ops/s
Bernd M¨uller 19.4.2016 27/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Internte Strings
Internte Strings
Bernd M¨uller 19.4.2016 28/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Internte Strings
Was ist das ?
Internte Strings — Was ist das ?
Bernd M¨uller 19.4.2016 29/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Internte Strings
Was ist das ?
Internte Strings
Moreover, a string literal always refers to the same instance of
class String. This is because string literals - or, more generally,
strings that are the values of constant expressions (§15.28) - are
”interned” so as to share unique instances, using the method
String.intern. [JLS 3.10.5 String Literals]
Bernd M¨uller 19.4.2016 30/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Internte Strings
Was ist das ?
Internte Strings
Moreover, a string literal always refers to the same instance of
class String. This is because string literals - or, more generally,
strings that are the values of constant expressions (§15.28) - are
”interned” so as to share unique instances, using the method
String.intern. [JLS 3.10.5 String Literals]
String-Memory-Pool mit allen internten Strings
Bernd M¨uller 19.4.2016 30/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Internte Strings
Was ist das ?
Internte Strings
Moreover, a string literal always refers to the same instance of
class String. This is because string literals - or, more generally,
strings that are the values of constant expressions (§15.28) - are
”interned” so as to share unique instances, using the method
String.intern. [JLS 3.10.5 String Literals]
String-Memory-Pool mit allen internten Strings
Beim Laden einer Klasse in die VM wird gepr¨uft, ob
String-Literal schon im Pool
Bernd M¨uller 19.4.2016 30/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Internte Strings
Was ist das ?
Internte Strings
Moreover, a string literal always refers to the same instance of
class String. This is because string literals - or, more generally,
strings that are the values of constant expressions (§15.28) - are
”interned” so as to share unique instances, using the method
String.intern. [JLS 3.10.5 String Literals]
String-Memory-Pool mit allen internten Strings
Beim Laden einer Klasse in die VM wird gepr¨uft, ob
String-Literal schon im Pool
Falls ja, wird es wiederverwendet, falls nein, neu eingetragen
Bernd M¨uller 19.4.2016 30/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Internte Strings
Was ist das ?
Internte Strings
Moreover, a string literal always refers to the same instance of
class String. This is because string literals - or, more generally,
strings that are the values of constant expressions (§15.28) - are
”interned” so as to share unique instances, using the method
String.intern. [JLS 3.10.5 String Literals]
String-Memory-Pool mit allen internten Strings
Beim Laden einer Klasse in die VM wird gepr¨uft, ob
String-Literal schon im Pool
Falls ja, wird es wiederverwendet, falls nein, neu eingetragen
String-Literale gibt es also nur einmal in einer VM
Bernd M¨uller 19.4.2016 30/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Internte Strings
Was ist das ?
Internte String-Literale — Beispiele
String str1 = Hello , World!;
String str2 = Hello , World!;
String str3 = new String(Hello , World!); // sinnlos
Assert.assertSame(Hello , World!, Hello , World!);
Assert.assertSame(str1 , str2 );
Assert.assertSame(Hel + lo, Hel + lo);
Assert.assertNotSame(str1 + str1 , str2 + str2 );
Assert.assertEquals(str1 + str1 , str2 + str2 );
Assert.assertSame (( str1 + str1 ). intern (),
(str2 + str2 ). intern ());
Assert.assertNotSame(str1 , str3 );
Bernd M¨uller 19.4.2016 31/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Internte Strings
Am¨usantes
Am¨usantes
Bernd M¨uller 19.4.2016 32/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Internte Strings
Am¨usantes
Spielereien
Was ist die Ausgabe?
System.out.println(Hello , World!);
magic ();
System.out.println(Hello , World!);
Bernd M¨uller 19.4.2016 33/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Internte Strings
Am¨usantes
Spielereien
Was ist die Ausgabe?
System.out.println(Hello , World!);
magic ();
System.out.println(Hello , World!);
private static void magic () throws Exception {
Field field = String.class
. getDeclaredField (value);
field.setAccessible(true );
field.set(Hello , World!,
tricky intern.toCharArray ());
}
Zuerst gesehen bei Arno Haase
Bernd M¨uller 19.4.2016 33/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Internte Strings
Am¨usantes
Spielereien
Was ist die Ausgabe?
System.out.println(Hello , World!);
magic ();
System.out.println(Hello , World!);
private static void magic () throws Exception {
Field field = String.class
. getDeclaredField (value);
field.setAccessible(true );
field.set(Hello , World!,
tricky intern.toCharArray ());
}
Zuerst gesehen bei Arno Haase
Bitte nicht nachmachen
Bernd M¨uller 19.4.2016 33/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Internte Strings
Am¨usantes
Spielereien (cont’d)
Was ist die Ausgabe?
System.out.println(Hello , World!);
magic ();
System.out.println(Hello , World!);
public static void magic () throws Exception {
Field field = String.class
. getDeclaredField (value);
field.setAccessible(true );
char [] chars = (char []) field.get(Hello World);
System.arraycopy(tricky intern.toCharArray (),
0, chars , 0, chars.length );
}
Bernd M¨uller 19.4.2016 34/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Internte Strings
Am¨usantes
Spielereien (cont’d)
Was ist die Ausgabe?
System.out.println(Hello , World!);
magic ();
System.out.println(Hello , World!);
public static void magic () throws Exception {
Field field = String.class
. getDeclaredField (value);
field.setAccessible(true );
char [] chars = (char []) field.get(Hello World);
System.arraycopy(tricky intern.toCharArray (),
0, chars , 0, chars.length );
}
Ebenfalls nicht nachmachen
Bernd M¨uller 19.4.2016 34/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Internte Strings
Nochmal Performanz
Nochmal Performanz
Bernd M¨uller 19.4.2016 35/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Internte Strings
Nochmal Performanz
Java-Doc String.intern()
Returns a canonical representation for the string object.
A pool of strings, initially empty, is maintained privately by the class
String.
When the intern method is invoked, if the pool already contains a string
equal to this String object as determined by the equals(Object) method,
then the string from the pool is returned. Otherwise, this String object is
added to the pool and a reference to this String object is returned.
It follows that for any two strings s and t, s.intern() == t.intern() is true
if and only if s.equals(t) is true.
All literal strings and string-valued constant expressions are interned.
String literals are defined in section 3.10.5 of the The JavaTM
Language
Specification.
Returns: a string that has the same contents as this string, but is
guaranteed to be from a pool of unique strings.
Bernd M¨uller 19.4.2016 36/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Internte Strings
Nochmal Performanz
Java-Doc String.intern()
Returns a canonical representation for the string object.
A pool of strings, initially empty, is maintained privately by the class
String.
When the intern method is invoked, if the pool already contains a string
equal to this String object as determined by the equals(Object) method,
then the string from the pool is returned. Otherwise, this String object is
added to the pool and a reference to this String object is returned.
It follows that for any two strings s and t, s.intern() == t.intern() is true
if and only if s.equals(t) is true.
All literal strings and string-valued constant expressions are interned.
String literals are defined in section 3.10.5 of the The JavaTM
Language
Specification.
Returns: a string that has the same contents as this string, but is
guaranteed to be from a pool of unique strings.
Bernd M¨uller 19.4.2016 36/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Internte Strings
Nochmal Performanz
Java-Doc String.intern()
Returns a canonical representation for the string object.
A pool of strings, initially empty, is maintained privately by the class
String.
When the intern method is invoked, if the pool already contains a string
equal to this String object as determined by the equals(Object) method,
then the string from the pool is returned. Otherwise, this String object is
added to the pool and a reference to this String object is returned.
It follows that for any two strings s and t, s.intern() == t.intern() is true
if and only if s.equals(t) is true.
All literal strings and string-valued constant expressions are interned.
String literals are defined in section 3.10.5 of the The JavaTM
Language
Specification.
Returns: a string that has the same contents as this string, but is
guaranteed to be from a pool of unique strings.
Bernd M¨uller 19.4.2016 36/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Internte Strings
Nochmal Performanz
Java-Doc String.intern()
Returns a canonical representation for the string object.
A pool of strings, initially empty, is maintained privately by the class
String.
When the intern method is invoked, if the pool already contains a string
equal to this String object as determined by the equals(Object) method,
then the string from the pool is returned. Otherwise, this String object is
added to the pool and a reference to this String object is returned.
It follows that for any two strings s and t, s.intern() == t.intern() is true
if and only if s.equals(t) is true.
All literal strings and string-valued constant expressions are interned.
String literals are defined in section 3.10.5 of the The JavaTM
Language
Specification.
Returns: a string that has the same contents as this string, but is
guaranteed to be from a pool of unique strings.
Bernd M¨uller 19.4.2016 36/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Internte Strings
Nochmal Performanz
Java-Doc String.intern()
Returns a canonical representation for the string object.
A pool of strings, initially empty, is maintained privately by the class
String.
When the intern method is invoked, if the pool already contains a string
equal to this String object as determined by the equals(Object) method,
then the string from the pool is returned. Otherwise, this String object is
added to the pool and a reference to this String object is returned.
It follows that for any two strings s and t, s.intern() == t.intern() is true
if and only if s.equals(t) is true.
All literal strings and string-valued constant expressions are interned.
String literals are defined in section 3.10.5 of the The JavaTM
Language
Specification.
Returns: a string that has the same contents as this string, but is
guaranteed to be from a pool of unique strings.
Bernd M¨uller 19.4.2016 36/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Internte Strings
Nochmal Performanz
Performanz-Idee: String-Interning und Equals
”
On the topic of interning strings, what about using the intern()
method to make the programm run faster, since interned strings
can be compared via the == operator? That is a popular thought,
though in most cases it turns out to by a myth. The
String.equals() method is pretty fast.
. . .
Comparing strings via the == operator is undeniably faster, but the
cost of interning the string must also be taken into consideration.“
[Java Performance, Scott Oaks]
Bernd M¨uller 19.4.2016 37/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Internte Strings
Nochmal Performanz
Performanz-Idee: String-Interning und Equals
”
On the topic of interning strings, what about using the intern()
method to make the programm run faster, since interned strings
can be compared via the == operator? That is a popular thought,
though in most cases it turns out to by a myth. The
String.equals() method is pretty fast.
. . .
Comparing strings via the == operator is undeniably faster, but the
cost of interning the string must also be taken into consideration.“
[Java Performance, Scott Oaks]
Bernd M¨uller 19.4.2016 37/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Internte Strings
Nochmal Performanz
Performanz-Idee: String-Interning und Equals
”
On the topic of interning strings, what about using the intern()
method to make the programm run faster, since interned strings
can be compared via the == operator? That is a popular thought,
though in most cases it turns out to by a myth. The
String.equals() method is pretty fast.
. . .
Comparing strings via the == operator is undeniably faster, but the
cost of interning the string must also be taken into consideration.“
[Java Performance, Scott Oaks]
Bernd M¨uller 19.4.2016 37/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Internte Strings
Nochmal Performanz
Performanz-Idee: String-Interning und Equals
”
On the topic of interning strings, what about using the intern()
method to make the programm run faster, since interned strings
can be compared via the == operator? That is a popular thought,
though in most cases it turns out to by a myth. The
String.equals() method is pretty fast.
. . .
Comparing strings via the == operator is undeniably faster, but the
cost of interning the string must also be taken into consideration.“
[Java Performance, Scott Oaks]
Bernd M¨uller 19.4.2016 37/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Internte Strings
Nochmal Performanz
Java Performance, Scott Oaks
”
Like most optimizations, interning strings shouldn’t
be done arbitrarily, but it can be effective if there are lots
of duplicate strings occupying a significant portion of the
heap.“
Bernd M¨uller 19.4.2016 38/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Internte Strings
Und nochmal Performanz
Und nochmal Performanz
Bernd M¨uller 19.4.2016 39/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Internte Strings
Und nochmal Performanz
Auch bitte nicht selbst versuchen: MyString
”
In compiler theory, an intrinsic function is a function available for
use in a given programming language whose implementation is
handled specially by the compiler. Typically, it substitutes a
sequence of automatically generated instructions for the original
function call, similar to an inline function. Unlike an inline function
though, the compiler has an intimate knowledge of the intrinsic
function and can therefore better integrate it and optimize it for
the situation.“[Wikipedia,Intr1]
Bernd M¨uller 19.4.2016 40/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Internte Strings
Und nochmal Performanz
Auch bitte nicht selbst versuchen: MyString
”
In compiler theory, an intrinsic function is a function available for
use in a given programming language whose implementation is
handled specially by the compiler. Typically, it substitutes a
sequence of automatically generated instructions for the original
function call, similar to an inline function. Unlike an inline function
though, the compiler has an intimate knowledge of the intrinsic
function and can therefore better integrate it and optimize it for
the situation.“[Wikipedia,Intr1]
Bernd M¨uller 19.4.2016 40/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Internte Strings
Und nochmal Performanz
Auch bitte nicht selbst versuchen: MyString
”
In compiler theory, an intrinsic function is a function available for
use in a given programming language whose implementation is
handled specially by the compiler. Typically, it substitutes a
sequence of automatically generated instructions for the original
function call, similar to an inline function. Unlike an inline function
though, the compiler has an intimate knowledge of the intrinsic
function and can therefore better integrate it and optimize it for
the situation.“[Wikipedia,Intr1]
Bernd M¨uller 19.4.2016 40/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Internte Strings
Und nochmal Performanz
Auch bitte nicht selbst versuchen: MyString
”
In compiler theory, an intrinsic function is a function available for
use in a given programming language whose implementation is
handled specially by the compiler. Typically, it substitutes a
sequence of automatically generated instructions for the original
function call, similar to an inline function. Unlike an inline function
though, the compiler has an intimate knowledge of the intrinsic
function and can therefore better integrate it and optimize it for
the situation.“[Wikipedia,Intr1]
In Java Compiler, JIT, evtl. sogar in JVM eingebaut
Bernd M¨uller 19.4.2016 40/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Internte Strings
Und nochmal Performanz
Auch bitte nicht selbst versuchen: MyString
”
In compiler theory, an intrinsic function is a function available for
use in a given programming language whose implementation is
handled specially by the compiler. Typically, it substitutes a
sequence of automatically generated instructions for the original
function call, similar to an inline function. Unlike an inline function
though, the compiler has an intimate knowledge of the intrinsic
function and can therefore better integrate it and optimize it for
the situation.“[Wikipedia,Intr1]
In Java Compiler, JIT, evtl. sogar in JVM eingebaut
String.equals() ist intrinsic. String.indexOf(),
String.compareTo() ebenfalls [Krystal Mo,Intr2]
String.intern() ist sogar nativ implementiert
Bernd M¨uller 19.4.2016 40/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Internte Strings
Implementierung
Implementierung
Bernd M¨uller 19.4.2016 41/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Internte Strings
Implementierung
Der String-Pool
Implementiert als Hashtable fester Gr¨oße
Bernd M¨uller 19.4.2016 42/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Internte Strings
Implementierung
Der String-Pool
Implementiert als Hashtable fester Gr¨oße
Bucket-Gr¨oße ab Java 6 einstellbar
Bernd M¨uller 19.4.2016 42/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Internte Strings
Implementierung
Der String-Pool
Implementiert als Hashtable fester Gr¨oße
Bucket-Gr¨oße ab Java 6 einstellbar
Nativ in JVM realisiert, Gr¨oße nicht ver¨anderbar
Bernd M¨uller 19.4.2016 42/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Internte Strings
Implementierung
Der String-Pool
Implementiert als Hashtable fester Gr¨oße
Bucket-Gr¨oße ab Java 6 einstellbar
Nativ in JVM realisiert, Gr¨oße nicht ver¨anderbar
In Java 6 in Permanent Generation, 7 und h¨oher im Heap
Bernd M¨uller 19.4.2016 42/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Internte Strings
Implementierung
Der String-Pool
Implementiert als Hashtable fester Gr¨oße
Bucket-Gr¨oße ab Java 6 einstellbar
Nativ in JVM realisiert, Gr¨oße nicht ver¨anderbar
In Java 6 in Permanent Generation, 7 und h¨oher im Heap
Daher in Java 6 OOME: PermGen space
Bernd M¨uller 19.4.2016 42/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Internte Strings
Implementierung
Der String-Pool
Implementiert als Hashtable fester Gr¨oße
Bucket-Gr¨oße ab Java 6 einstellbar
Nativ in JVM realisiert, Gr¨oße nicht ver¨anderbar
In Java 6 in Permanent Generation, 7 und h¨oher im Heap
Daher in Java 6 OOME: PermGen space
Java 7 und h¨oher OOME: Java heap space
Bernd M¨uller 19.4.2016 42/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Internte Strings
Implementierung
Der String-Pool
Implementiert als Hashtable fester Gr¨oße
Bucket-Gr¨oße ab Java 6 einstellbar
Nativ in JVM realisiert, Gr¨oße nicht ver¨anderbar
In Java 6 in Permanent Generation, 7 und h¨oher im Heap
Daher in Java 6 OOME: PermGen space
Java 7 und h¨oher OOME: Java heap space
Gr¨oßen:
Bernd M¨uller 19.4.2016 42/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Internte Strings
Implementierung
Der String-Pool
Implementiert als Hashtable fester Gr¨oße
Bucket-Gr¨oße ab Java 6 einstellbar
Nativ in JVM realisiert, Gr¨oße nicht ver¨anderbar
In Java 6 in Permanent Generation, 7 und h¨oher im Heap
Daher in Java 6 OOME: PermGen space
Java 7 und h¨oher OOME: Java heap space
Gr¨oßen:
Vor Java 7u40 1009 Buckets
Bernd M¨uller 19.4.2016 42/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Internte Strings
Implementierung
Der String-Pool
Implementiert als Hashtable fester Gr¨oße
Bucket-Gr¨oße ab Java 6 einstellbar
Nativ in JVM realisiert, Gr¨oße nicht ver¨anderbar
In Java 6 in Permanent Generation, 7 und h¨oher im Heap
Daher in Java 6 OOME: PermGen space
Java 7 und h¨oher OOME: Java heap space
Gr¨oßen:
Vor Java 7u40 1009 Buckets
Java 7u40 und sp¨ater 60013
Bernd M¨uller 19.4.2016 42/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Internte Strings
Implementierung
Der String-Pool
Implementiert als Hashtable fester Gr¨oße
Bucket-Gr¨oße ab Java 6 einstellbar
Nativ in JVM realisiert, Gr¨oße nicht ver¨anderbar
In Java 6 in Permanent Generation, 7 und h¨oher im Heap
Daher in Java 6 OOME: PermGen space
Java 7 und h¨oher OOME: Java heap space
Gr¨oßen:
Vor Java 7u40 1009 Buckets
Java 7u40 und sp¨ater 60013
VM-Schalter:
Bernd M¨uller 19.4.2016 42/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Internte Strings
Implementierung
Der String-Pool
Implementiert als Hashtable fester Gr¨oße
Bucket-Gr¨oße ab Java 6 einstellbar
Nativ in JVM realisiert, Gr¨oße nicht ver¨anderbar
In Java 6 in Permanent Generation, 7 und h¨oher im Heap
Daher in Java 6 OOME: PermGen space
Java 7 und h¨oher OOME: Java heap space
Gr¨oßen:
Vor Java 7u40 1009 Buckets
Java 7u40 und sp¨ater 60013
VM-Schalter:
-XX:StringTableSize=value
Bernd M¨uller 19.4.2016 42/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Internte Strings
Implementierung
Der String-Pool
Implementiert als Hashtable fester Gr¨oße
Bucket-Gr¨oße ab Java 6 einstellbar
Nativ in JVM realisiert, Gr¨oße nicht ver¨anderbar
In Java 6 in Permanent Generation, 7 und h¨oher im Heap
Daher in Java 6 OOME: PermGen space
Java 7 und h¨oher OOME: Java heap space
Gr¨oßen:
Vor Java 7u40 1009 Buckets
Java 7u40 und sp¨ater 60013
VM-Schalter:
-XX:StringTableSize=value
-XX:+PrintStringTableStatistics (Java 7u6 und gr¨oßer,
6u32 Backport)
Bernd M¨uller 19.4.2016 42/60
Beispiele -XX:+PrintStringTableStatistics
StringTable statistics:
Number of buckets : 1003
Average bucket size : 33
Variance of bucket size : 33
Std. dev. of bucket size: 6
Maximum bucket size : 51
Beispiele -XX:+PrintStringTableStatistics
StringTable statistics:
Number of buckets : 1003
Average bucket size : 33
Variance of bucket size : 33
Std. dev. of bucket size: 6
Maximum bucket size : 51
Beispiele -XX:+PrintStringTableStatistics
StringTable statistics:
Number of buckets : 1003
Average bucket size : 33
Variance of bucket size : 33
Std. dev. of bucket size: 6
Maximum bucket size : 51
Schlecht
StringTable statistics:
Number of buckets : 60013
Average bucket size : 1
Variance of bucket size : 1
Std. dev. of bucket size: 1
Maximum bucket size : 10
Beispiele -XX:+PrintStringTableStatistics
StringTable statistics:
Number of buckets : 1003
Average bucket size : 33
Variance of bucket size : 33
Std. dev. of bucket size: 6
Maximum bucket size : 51
Schlecht
StringTable statistics:
Number of buckets : 60013
Average bucket size : 1
Variance of bucket size : 1
Std. dev. of bucket size: 1
Maximum bucket size : 10
Beispiele -XX:+PrintStringTableStatistics
StringTable statistics:
Number of buckets : 1003
Average bucket size : 33
Variance of bucket size : 33
Std. dev. of bucket size: 6
Maximum bucket size : 51
Schlecht
StringTable statistics:
Number of buckets : 60013
Average bucket size : 1
Variance of bucket size : 1
Std. dev. of bucket size: 1
Maximum bucket size : 10Viel besser
StringTable statistics:
Number of buckets : 60013
Average bucket size : 0
Variance of bucket size : 0
Std. dev. of bucket size: 1
Maximum bucket size : 5
Beispiele -XX:+PrintStringTableStatistics
StringTable statistics:
Number of buckets : 1003
Average bucket size : 33
Variance of bucket size : 33
Std. dev. of bucket size: 6
Maximum bucket size : 51
Schlecht
StringTable statistics:
Number of buckets : 60013
Average bucket size : 1
Variance of bucket size : 1
Std. dev. of bucket size: 1
Maximum bucket size : 10Viel besser
StringTable statistics:
Number of buckets : 60013
Average bucket size : 0
Variance of bucket size : 0
Std. dev. of bucket size: 1
Maximum bucket size : 5
Beispiele -XX:+PrintStringTableStatistics
StringTable statistics:
Number of buckets : 1003
Average bucket size : 33
Variance of bucket size : 33
Std. dev. of bucket size: 6
Maximum bucket size : 51
Schlecht
StringTable statistics:
Number of buckets : 60013
Average bucket size : 1
Variance of bucket size : 1
Std. dev. of bucket size: 1
Maximum bucket size : 10Viel besser
StringTable statistics:
Number of buckets : 60013
Average bucket size : 0
Variance of bucket size : 0
Std. dev. of bucket size: 1
Maximum bucket size : 5
Empfehlenswert
In Java 8 ausf¨uhrlichere Informationen
StringTable statistics:
Number of buckets : 60013 = 480104 bytes , avg 8,000
Number of entries : 797 = 19128 bytes , avg 24 ,000
Number of literals : 797 = 151960 bytes , avg 190 ,665
Total footprint : = 651192 bytes
Average bucket size : 0,013
Variance of bucket size : 0,013
Std. dev. of bucket size: 0,115
Maximum bucket size : 2
Was jeder Java-Entwickler ¨uber Strings wissen sollte
GC1 String-Deduplication
GC1 + JVM-Optionen
Bernd M¨uller 19.4.2016 45/60
JEP 192: String Deduplication in G1 [JEP192]
Summary
”
Reduce the Java heap live-data set by enhancing the G1 garbage
collector so that duplicate instances of String are automatically
and continuously deduplicated. “
JEP 192: String Deduplication in G1 [JEP192]
Summary
”
Reduce the Java heap live-data set by enhancing the G1 garbage
collector so that duplicate instances of String are automatically
and continuously deduplicated. “
Motivation
”
. . . Measurements have shown that roughly 25% of the Java heap
live data set in these types of applications is consumed by String
objects. . . . roughly half of those String objects are duplicates
. . . Having duplicate String objects on the heap is, essentially, just
a waste of memory“
JEP 192: String Deduplication in G1 [JEP192]
Summary
”
Reduce the Java heap live-data set by enhancing the G1 garbage
collector so that duplicate instances of String are automatically
and continuously deduplicated. “
Motivation
”
. . . Measurements have shown that roughly 25% of the Java heap
live data set in these types of applications is consumed by String
objects. . . . roughly half of those String objects are duplicates
. . . Having duplicate String objects on the heap is, essentially, just
a waste of memory“
Description
”
The value field is implementation-specific and not observable
from outside . . . This means that it can safely and transparently be
used by multiple instances of String at the same time.
JEP 192: String Deduplication in G1 [JEP192]
Summary
”
Reduce the Java heap live-data set by enhancing the G1 garbage
collector so that duplicate instances of String are automatically
and continuously deduplicated. “
Motivation
”
. . . Measurements have shown that roughly 25% of the Java heap
live data set in these types of applications is consumed by String
objects. . . . roughly half of those String objects are duplicates
. . . Having duplicate String objects on the heap is, essentially, just
a waste of memory“
Description
”
The value field is implementation-specific and not observable
from outside . . . This means that it can safely and transparently be
used by multiple instances of String at the same time.
Deduplicating a String object is conceptually just an re-assignment
of the value field, i.e., aString.value = anotherString.value.
-XX:+UseG1GC -XX:+UseStringDeduplication
String tmp = some string;
String string1 = new String(tmp + tmp);
String string2 = new String(tmp + tmp);
Field field = String.class. getDeclaredField (value);
field.setAccessible(true );
Assert.assertEquals(string1 , string2 );
Assert.assertNotSame(string1 , string2 );
Assert.assertNotSame(field.get(string1),
field.get(string2 ));
System.gc();
Thread.sleep (1000);
Assert.assertNotSame(string1 , string2 );
Assert.assertSame(field.get(string1),
field.get(string2 ));
Was jeder Java-Entwickler ¨uber Strings wissen sollte
GC1 String-Deduplication
Erfahrungsbericht
Artikel G1: from garbage collector to waste management
consultant
von Erik Costlow, 24.3.2016, Java Platform Group, Product
Management blog
Aussage: String Deduplication may decrease heap usage by
about 10%
Am Beispiel Eclipse
Referenz: [DEDUP]
Bernd M¨uller 19.4.2016 48/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Dies und das
Dies und das
Bernd M¨uller 19.4.2016 49/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Dies und das
Heinz Kabutz, Reflection Madness, JAX London 2014
Java 1.0 - 1.2
String contained char[], offset, count
Java 1.3 - 1.6
Added a cached hash code
String became a shared, mutable, but thread-safe class
Java 1.7
Got rid of offset and length and added hash32
Java 1.8
Got rid of hash32 again
Bernd M¨uller 19.4.2016 50/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Dies und das
Andere String-relevante VM-Optionen
-XX:+UseStringCache
”
Enables caching of commonly allocated strings.“
Keine weiteren Informationen gefunden. Vorhanden in Java 6
und 7. Entfernt in Java 8
Bernd M¨uller 19.4.2016 51/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Dies und das
Andere String-relevante VM-Optionen
-XX:+UseStringCache
”
Enables caching of commonly allocated strings.“
Keine weiteren Informationen gefunden. Vorhanden in Java 6
und 7. Entfernt in Java 8
-XX:+UseCompressedStrings
”
Use a byte[] for Strings which can be represented as pure
ASCII.“
Eingef¨uhrt in Java 6u21. Wieder entfernt in Java 7
Bernd M¨uller 19.4.2016 51/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Dies und das
Andere String-relevante VM-Optionen
-XX:+UseStringCache
”
Enables caching of commonly allocated strings.“
Keine weiteren Informationen gefunden. Vorhanden in Java 6
und 7. Entfernt in Java 8
-XX:+UseCompressedStrings
”
Use a byte[] for Strings which can be represented as pure
ASCII.“
Eingef¨uhrt in Java 6u21. Wieder entfernt in Java 7
-XX:+OptimizeStringConcat
”
Optimize String concatenation operations where possible.“
Eingef¨uhrt in Java 6u20. Optimiert wiederholte StringBuilder
append()-Aufrufe
Bernd M¨uller 19.4.2016 51/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Dies und das
Ausblick — es geht immer weiter . . .
JEP 254: Compact Strings [JEP254]
Bernd M¨uller 19.4.2016 52/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Dies und das
Ausblick — es geht immer weiter . . .
JEP 254: Compact Strings [JEP254]
Bereits 8/2014 definiert
Bernd M¨uller 19.4.2016 52/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Dies und das
Ausblick — es geht immer weiter . . .
JEP 254: Compact Strings [JEP254]
Bereits 8/2014 definiert
”
Wiederbelebung“ von -XX:+UseCompressedStrings
Bernd M¨uller 19.4.2016 52/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Dies und das
Ausblick — es geht immer weiter . . .
JEP 254: Compact Strings [JEP254]
Bereits 8/2014 definiert
”
Wiederbelebung“ von -XX:+UseCompressedStrings
kodiert Zeichen als ISO-8859-1/Latin-1 (1 Byte pro Zeichen)
oder UTF-16 (2 Bytes pro Zeichen)
Bernd M¨uller 19.4.2016 52/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Dies und das
Ausblick — es geht immer weiter . . .
JEP 254: Compact Strings [JEP254]
Bereits 8/2014 definiert
”
Wiederbelebung“ von -XX:+UseCompressedStrings
kodiert Zeichen als ISO-8859-1/Latin-1 (1 Byte pro Zeichen)
oder UTF-16 (2 Bytes pro Zeichen)
Marker zur Kennzeichnung
Bernd M¨uller 19.4.2016 52/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Dies und das
Ausblick — es geht immer weiter . . .
JEP 254: Compact Strings [JEP254]
Bereits 8/2014 definiert
”
Wiederbelebung“ von -XX:+UseCompressedStrings
kodiert Zeichen als ISO-8859-1/Latin-1 (1 Byte pro Zeichen)
oder UTF-16 (2 Bytes pro Zeichen)
Marker zur Kennzeichnung
JavaOne 2015, CON5483: Compact Strings: A
Memory-Efficient Internal Representation for Strings
Bernd M¨uller 19.4.2016 52/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Dies und das
Ausblick — es geht immer weiter . . .
JEP 254: Compact Strings [JEP254]
Bereits 8/2014 definiert
”
Wiederbelebung“ von -XX:+UseCompressedStrings
kodiert Zeichen als ISO-8859-1/Latin-1 (1 Byte pro Zeichen)
oder UTF-16 (2 Bytes pro Zeichen)
Marker zur Kennzeichnung
JavaOne 2015, CON5483: Compact Strings: A
Memory-Efficient Internal Representation for Strings
Gemeinsames Projekt von Oracle und Intel, 10+ Entwickler
Bernd M¨uller 19.4.2016 52/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Dies und das
Ausblick — es geht immer weiter . . .
JEP 254: Compact Strings [JEP254]
Bereits 8/2014 definiert
”
Wiederbelebung“ von -XX:+UseCompressedStrings
kodiert Zeichen als ISO-8859-1/Latin-1 (1 Byte pro Zeichen)
oder UTF-16 (2 Bytes pro Zeichen)
Marker zur Kennzeichnung
JavaOne 2015, CON5483: Compact Strings: A
Memory-Efficient Internal Representation for Strings
Gemeinsames Projekt von Oracle und Intel, 10+ Entwickler
Kommt in Java 9. In neueren EAs enthalten
Bernd M¨uller 19.4.2016 52/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Dies und das
Wer an Schnittstellen vorbei programmiert,
ist selbst schuld . . .
Große Diskussion: sun.misc.Unsafe
Bernd M¨uller 19.4.2016 53/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Dies und das
Wer an Schnittstellen vorbei programmiert,
ist selbst schuld . . .
Große Diskussion: sun.misc.Unsafe
Hier: magic(), in Abschnitt Am¨usantes
Bernd M¨uller 19.4.2016 53/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Dies und das
Wer an Schnittstellen vorbei programmiert,
ist selbst schuld . . .
Große Diskussion: sun.misc.Unsafe
Hier: magic(), in Abschnitt Am¨usantes
. . . schauen wir uns die Details an . . .
Bernd M¨uller 19.4.2016 53/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Dies und das
String-Interna vor JEP 254
/** The value is used for character storage. */
private final char value [];
Bernd M¨uller 19.4.2016 54/60
String-Interna nach JEP 254
/**
* The value is used for character storage .
*
* @implNote This field is trusted by the VM , and is a subject to
* constant folding if String instance is constant . Overwriting this
* field after construction will cause problems .
*
* Additionally , it is marked with { @link Stable } to trust the contents
* of the array. No other facility in JDK provides this functionality (yet ).
* {@link Stable } is safe here , because value is never null.
*/
@Stable
private final byte [] value;
/**
* The identifier of the encoding used to encode the bytes in
* {@code value }. The supported values in this implementation are
*
* LATIN1
* UTF16
*
* @implNote This field is trusted by the VM , and is a subject to
* constant folding if String instance is constant . Overwriting this
* field after construction will cause problems .
*/
private final byte coder;
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Dies und das
magic() ¨uberarbeitet
Wirft mit Java 9 Exception:
java.lang. IllegalArgumentException : Can not set
final [B field java.lang.String.value to [C
Bernd M¨uller 19.4.2016 56/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Dies und das
magic() ¨uberarbeitet
Wirft mit Java 9 Exception:
java.lang. IllegalArgumentException : Can not set
final [B field java.lang.String.value to [C
¨Uberarbeitung: aus
private static void magic () throws Exception {
Field field = String.class. getDeclaredField (value);
field. setAccessible (true );
field.set(Hello , World!, tricky intern.toCharArray ());
}
wird
private static void magic () throws Exception {
Field field = String.class. getDeclaredField (value);
field. setAccessible (true );
field.set(Hello , World!, tricky intern.getBytes ());
}
Bernd M¨uller 19.4.2016 56/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Fragen und Anmerkungen
Fragen und Anmerkungen
Bernd M¨uller 19.4.2016 57/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Referenzen
Referenzen
Bernd M¨uller 19.4.2016 58/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Referenzen
Referenzen
[Gonc] Antonio Goncalves: Who Cares About toString
Performance?
[Intr1] Wikipedia: Intrinsic function
[Intr2] Krystal Mo. Intrinsic Methods in HotSpot VM
[Bug1] JDK-6962931: move interned strings out of the perm gen
[Bug2] JDK-6964458: Reimplement class meta-data storage to use
native memory
[Bug3] JDK-4513622: (str) keeping a substring of a field prevents
GC for object
[JEP192] JEP 192: String Deduplication in G1
[JEP254] JEP 254: Compact Strings
[DEDUP] G1: from garbage collector to waste management
consultant
Bernd M¨uller 19.4.2016 59/60
Was jeder Java-Entwickler ¨uber Strings wissen sollte
Referenzen
Referenzen (cont’d)
[CHAR1] Supplementary Characters in the Java Platform
[CHAR2] Supplementary Characters as Surrogates
[CHAR3] Unicode Character Representations
[CHAR4] Supported Encodings
[CHAR5] Unicode 4.0 support in J2SE 1.5
Bernd M¨uller 19.4.2016 60/60

Weitere ähnliche Inhalte

Andere mochten auch

Andere mochten auch (10)

A donde iré sin ti señor
A donde iré sin ti señorA donde iré sin ti señor
A donde iré sin ti señor
 
Sistemas operativos
Sistemas operativosSistemas operativos
Sistemas operativos
 
RidgeGarrett_App_Services_brochure
RidgeGarrett_App_Services_brochureRidgeGarrett_App_Services_brochure
RidgeGarrett_App_Services_brochure
 
Upload test
Upload testUpload test
Upload test
 
Diaz salas jessica gpe grupo 10
Diaz salas jessica gpe grupo 10Diaz salas jessica gpe grupo 10
Diaz salas jessica gpe grupo 10
 
interprete de sueños
interprete de sueños interprete de sueños
interprete de sueños
 
Img 0036
Img 0036Img 0036
Img 0036
 
Conselhos gestores
Conselhos gestoresConselhos gestores
Conselhos gestores
 
Laboratorio de Física II Principio de Arquimides
Laboratorio de Física II Principio de ArquimidesLaboratorio de Física II Principio de Arquimides
Laboratorio de Física II Principio de Arquimides
 
Análisis de puestos de trabajo
Análisis de puestos de trabajoAnálisis de puestos de trabajo
Análisis de puestos de trabajo
 

Mehr von berndmueller

Compilers Everywhere
Compilers EverywhereCompilers Everywhere
Compilers Everywhereberndmueller
 
JFN 2017 - Instrumentierung - Das Werkzeug der Werkzeugmacher
JFN 2017 - Instrumentierung - Das Werkzeug der WerkzeugmacherJFN 2017 - Instrumentierung - Das Werkzeug der Werkzeugmacher
JFN 2017 - Instrumentierung - Das Werkzeug der Werkzeugmacherberndmueller
 
Drohnen und WARP-Antriebe
Drohnen und WARP-AntriebeDrohnen und WARP-Antriebe
Drohnen und WARP-Antriebeberndmueller
 
Hasta la vista Mandantenfähigkeit?
Hasta la vista Mandantenfähigkeit?Hasta la vista Mandantenfähigkeit?
Hasta la vista Mandantenfähigkeit?berndmueller
 
Class Loading Revisited
Class Loading RevisitedClass Loading Revisited
Class Loading Revisitedberndmueller
 
Instrumentierung - Das Werkzeug der Werkzeugmacher -
Instrumentierung - Das Werkzeug der Werkzeugmacher - Instrumentierung - Das Werkzeug der Werkzeugmacher -
Instrumentierung - Das Werkzeug der Werkzeugmacher - berndmueller
 

Mehr von berndmueller (6)

Compilers Everywhere
Compilers EverywhereCompilers Everywhere
Compilers Everywhere
 
JFN 2017 - Instrumentierung - Das Werkzeug der Werkzeugmacher
JFN 2017 - Instrumentierung - Das Werkzeug der WerkzeugmacherJFN 2017 - Instrumentierung - Das Werkzeug der Werkzeugmacher
JFN 2017 - Instrumentierung - Das Werkzeug der Werkzeugmacher
 
Drohnen und WARP-Antriebe
Drohnen und WARP-AntriebeDrohnen und WARP-Antriebe
Drohnen und WARP-Antriebe
 
Hasta la vista Mandantenfähigkeit?
Hasta la vista Mandantenfähigkeit?Hasta la vista Mandantenfähigkeit?
Hasta la vista Mandantenfähigkeit?
 
Class Loading Revisited
Class Loading RevisitedClass Loading Revisited
Class Loading Revisited
 
Instrumentierung - Das Werkzeug der Werkzeugmacher -
Instrumentierung - Das Werkzeug der Werkzeugmacher - Instrumentierung - Das Werkzeug der Werkzeugmacher -
Instrumentierung - Das Werkzeug der Werkzeugmacher -
 

Was jeder Java-Entwickler über Strings wissen sollte

  • 1. Was jeder Java-Entwickler ¨uber Strings wissen sollte Was jeder Java-Entwickler ¨uber Strings wissen sollte Bernd M¨uller 19.4.2016 Bernd M¨uller 19.4.2016 1/60
  • 2. Was jeder Java-Entwickler ¨uber Strings wissen sollte Vor vielen, vielen Jahren . . . Vor vielen, vielen Jahren . . . Bernd M¨uller 19.4.2016 2/60
  • 3. Was jeder Java-Entwickler ¨uber Strings wissen sollte Vor vielen, vielen Jahren . . . Vor vielen, vielen Jahren . . . public class HelloWorld { public static void main(String [] args) { System.out.println("Hello World"); } } Bernd M¨uller 19.4.2016 3/60
  • 4. Was jeder Java-Entwickler ¨uber Strings wissen sollte Vor vielen, vielen Jahren . . . Vor vielen, vielen Jahren . . . public class HelloWorld { public static void main(String [] args) { System.out.println("Hello World"); } } Was ist ” String[]“ ? Was ist ” ”Hello World”“ ? Hat das irgend etwas miteinander zu tun ? Bernd M¨uller 19.4.2016 3/60
  • 5. Was jeder Java-Entwickler ¨uber Strings wissen sollte Referent Vorstellung Referent Prof. Informatik (Ostfalia, HS Braunschweig/Wolfenb¨uttel) Buchautor (JSF, Seam, JPA, ...) Mitglied EGs JSR 344 (JSF 2.2) und JSR 338 (JPA 2.1) Gesch¨aftsf¨uhrer PMST GmbH . . . Bernd M¨uller 19.4.2016 4/60
  • 6. Was jeder Java-Entwickler ¨uber Strings wissen sollte Motivation Motivation Bernd M¨uller 19.4.2016 5/60
  • 7. Was jeder Java-Entwickler ¨uber Strings wissen sollte Motivation Bernd M¨uller 19.4.2016 6/60
  • 8. Was jeder Java-Entwickler ¨uber Strings wissen sollte Motivation ¨ © Bernd M¨uller 19.4.2016 7/60
  • 9. Was jeder Java-Entwickler ¨uber Strings wissen sollte Motivation Auszug aus Abschnitt String Interning ” Strings are, far and away, the most common Java object; your application’s heap is almost certainly filled with them.“ Bernd M¨uller 19.4.2016 8/60
  • 10. Was jeder Java-Entwickler ¨uber Strings wissen sollte Motivation Bernd M¨uller 19.4.2016 9/60
  • 11. Was jeder Java-Entwickler ¨uber Strings wissen sollte Motivation 9 8 6 7 Bernd M¨uller 19.4.2016 10/60
  • 12. Was jeder Java-Entwickler ¨uber Strings wissen sollte Motivation Bernd M¨uller 19.4.2016 11/60
  • 13. Was jeder Java-Entwickler ¨uber Strings wissen sollte Motivation 9 8 6 7 Bernd M¨uller 19.4.2016 12/60
  • 14. Was jeder Java-Entwickler ¨uber Strings wissen sollte String-Klassen String-Klassen und -Methoden Bernd M¨uller 19.4.2016 13/60
  • 15. Was jeder Java-Entwickler ¨uber Strings wissen sollte String-Klassen Klassen mit String-Bezug: die ¨ublichen Verd¨achtigen java.lang.String, seit Java 1.0 The String class represents character strings. java.lang.StringBuffer, seit Java 1.0 A thread-safe, mutable sequence of characters. java.lang.StringBuilder, seit Java 5 A mutable sequence of characters. java.util.StringTokenizer, seit Java 1.0 The string tokenizer class allows an application to break a string into tokens. java.util.StringJoiner, seit Java 8 StringJoiner is used to construct a sequence of characters separated by a delimiter . . . Bernd M¨uller 19.4.2016 14/60
  • 16. Was jeder Java-Entwickler ¨uber Strings wissen sollte String-Klassen Klassen mit String-Bezug: die ¨ublichen Verd¨achtigen java.lang.String, seit Java 1.0 The String class represents character strings. java.lang.StringBuffer, seit Java 1.0 A thread-safe, mutable sequence of characters. java.lang.StringBuilder, seit Java 5 A mutable sequence of characters. java.util.StringTokenizer, seit Java 1.0 The string tokenizer class allows an application to break a string into tokens. java.util.StringJoiner, seit Java 8 StringJoiner is used to construct a sequence of characters separated by a delimiter . . . Bernd M¨uller 19.4.2016 14/60
  • 17. Was jeder Java-Entwickler ¨uber Strings wissen sollte String-Klassen Klassen mit String-Bezug: die ¨ublichen Verd¨achtigen java.lang.String, seit Java 1.0 The String class represents character strings. java.lang.StringBuffer, seit Java 1.0 A thread-safe, mutable sequence of characters. java.lang.StringBuilder, seit Java 5 A mutable sequence of characters. java.util.StringTokenizer, seit Java 1.0 The string tokenizer class allows an application to break a string into tokens. java.util.StringJoiner, seit Java 8 StringJoiner is used to construct a sequence of characters separated by a delimiter . . . Bernd M¨uller 19.4.2016 14/60
  • 18. Was jeder Java-Entwickler ¨uber Strings wissen sollte String-Klassen Klassen mit String-Bezug: die ¨ublichen Verd¨achtigen java.lang.String, seit Java 1.0 The String class represents character strings. java.lang.StringBuffer, seit Java 1.0 A thread-safe, mutable sequence of characters. java.lang.StringBuilder, seit Java 5 A mutable sequence of characters. java.util.StringTokenizer, seit Java 1.0 The string tokenizer class allows an application to break a string into tokens. java.util.StringJoiner, seit Java 8 StringJoiner is used to construct a sequence of characters separated by a delimiter . . . Bernd M¨uller 19.4.2016 14/60
  • 19. Was jeder Java-Entwickler ¨uber Strings wissen sollte String-Klassen Klassen mit String-Bezug: die ¨ublichen Verd¨achtigen java.lang.String, seit Java 1.0 The String class represents character strings. java.lang.StringBuffer, seit Java 1.0 A thread-safe, mutable sequence of characters. java.lang.StringBuilder, seit Java 5 A mutable sequence of characters. java.util.StringTokenizer, seit Java 1.0 The string tokenizer class allows an application to break a string into tokens. java.util.StringJoiner, seit Java 8 StringJoiner is used to construct a sequence of characters separated by a delimiter . . . Bernd M¨uller 19.4.2016 14/60
  • 20. Was jeder Java-Entwickler ¨uber Strings wissen sollte String-Klassen Padding Padding in der Regel mit Apache Commons-Lang StringUtils: leftPad(), rightPad() Bernd M¨uller 19.4.2016 15/60
  • 21. Was jeder Java-Entwickler ¨uber Strings wissen sollte String-Klassen Padding Padding in der Regel mit Apache Commons-Lang StringUtils: leftPad(), rightPad() Man ben¨otigt aber keine Bibliothek, ist im SDK eingebaut Schl¨ussel: java.util.Formatter als printf-Nachahmung Bernd M¨uller 19.4.2016 15/60
  • 22. Was jeder Java-Entwickler ¨uber Strings wissen sollte String-Klassen Padding Padding in der Regel mit Apache Commons-Lang StringUtils: leftPad(), rightPad() Man ben¨otigt aber keine Bibliothek, ist im SDK eingebaut Schl¨ussel: java.util.Formatter als printf-Nachahmung Beispiel: String.format(%1 $10s, hello) String.format(%1$-10s, hello) Bernd M¨uller 19.4.2016 15/60
  • 23. Was jeder Java-Entwickler ¨uber Strings wissen sollte Character-Codierungen Character-Codierungen Bernd M¨uller 19.4.2016 16/60
  • 24. Was jeder Java-Entwickler ¨uber Strings wissen sollte Character-Codierungen Character-Codierungen Historisch Java mit 16 Bit codiertem char-Datentyp Bernd M¨uller 19.4.2016 17/60
  • 25. Was jeder Java-Entwickler ¨uber Strings wissen sollte Character-Codierungen Character-Codierungen Historisch Java mit 16 Bit codiertem char-Datentyp Mit Java 5 wurde Unicode 4.0 als Character-Codierung eingef¨uhrt [CHAR1] Bernd M¨uller 19.4.2016 17/60
  • 26. Was jeder Java-Entwickler ¨uber Strings wissen sollte Character-Codierungen Character-Codierungen Historisch Java mit 16 Bit codiertem char-Datentyp Mit Java 5 wurde Unicode 4.0 als Character-Codierung eingef¨uhrt [CHAR1] Damit Codierungen mit mehr als 16 Bit m¨oglich, die als sogenannte Surrogate repr¨asentiert werden Bernd M¨uller 19.4.2016 17/60
  • 27. Was jeder Java-Entwickler ¨uber Strings wissen sollte Character-Codierungen Java Tutorial: Supplementary Characters as Surrogates ” To support supplementary characters without changing the char primitive data type and causing incompatibility with previous Java programs, supplementary characters are defined by a pair of code point values that are called surrogates. The first code point is from the high surrogates range of U+D800 to U+DFBB, and the second code point is from the low surrogates range of U+DC00 to U+DFFF. For example, the Deseret character LONG I, U+10400, is defined with this pair of surrogate values: U+D801 and U+DC00.“ [CHAR2] Bernd M¨uller 19.4.2016 18/60
  • 28. Was jeder Java-Entwickler ¨uber Strings wissen sollte Character-Codierungen Character-Codierungen (cont’d) Beschreibung in Java-Doc java.lang.Character [CHAR4] Bernd M¨uller 19.4.2016 19/60
  • 29. Was jeder Java-Entwickler ¨uber Strings wissen sollte Character-Codierungen Character-Codierungen (cont’d) Beschreibung in Java-Doc java.lang.Character [CHAR4] ¨Uberblick Java 1.4: Unicode 3.0 Java 5: Unicode 4.0 Java 6: Unicode 4.0 Java 7: Unicode 6.0.0 Java 8: Unicode 6.2.0 Java 9: Unicode 8.0.0 Bernd M¨uller 19.4.2016 19/60
  • 30. Was jeder Java-Entwickler ¨uber Strings wissen sollte Character-Codierungen Character-Codierungen (cont’d) Beschreibung in Java-Doc java.lang.Character [CHAR4] ¨Uberblick Java 1.4: Unicode 3.0 Java 5: Unicode 4.0 Java 6: Unicode 4.0 Java 7: Unicode 6.0.0 Java 8: Unicode 6.2.0 Java 9: Unicode 8.0.0 Basic Encodings in lib/rt.jar, Extended Encodings in lib/charsets.jar, Dokumentation in [CHAR3] Bernd M¨uller 19.4.2016 19/60
  • 31. Was jeder Java-Entwickler ¨uber Strings wissen sollte Performanz Performanz Bernd M¨uller 19.4.2016 20/60
  • 32. Was jeder Java-Entwickler ¨uber Strings wissen sollte Performanz Performanz: toString() Performanz: toString() Bernd M¨uller 19.4.2016 21/60
  • 33. Was jeder Java-Entwickler ¨uber Strings wissen sollte Performanz Performanz: toString() Who Cares About toString Performance ? Blog von Antonio Goncalves [Gonc] Bernd M¨uller 19.4.2016 22/60
  • 34. Was jeder Java-Entwickler ¨uber Strings wissen sollte Performanz Performanz: toString() Who Cares About toString Performance ? Blog von Antonio Goncalves [Gonc] Use Case: Großer Batch mit Logging und toString(), o.¨a. Bernd M¨uller 19.4.2016 22/60
  • 35. Was jeder Java-Entwickler ¨uber Strings wissen sollte Performanz Performanz: toString() Who Cares About toString Performance ? Blog von Antonio Goncalves [Gonc] Use Case: Großer Batch mit Logging und toString(), o.¨a. Effective Java [Joshua Bloch] Item 10: Always override toString Bernd M¨uller 19.4.2016 22/60
  • 36. Was jeder Java-Entwickler ¨uber Strings wissen sollte Performanz Performanz: toString() Who Cares About toString Performance ? Blog von Antonio Goncalves [Gonc] Use Case: Großer Batch mit Logging und toString(), o.¨a. Effective Java [Joshua Bloch] Item 10: Always override toString toString()-Methode durch IDE generiert oder selbst gemacht mit Alternativen Bernd M¨uller 19.4.2016 22/60
  • 37. Was jeder Java-Entwickler ¨uber Strings wissen sollte Performanz Performanz: toString() Who Cares About toString Performance ? Blog von Antonio Goncalves [Gonc] Use Case: Großer Batch mit Logging und toString(), o.¨a. Effective Java [Joshua Bloch] Item 10: Always override toString toString()-Methode durch IDE generiert oder selbst gemacht mit Alternativen Null-Checks nicht vergessen Bernd M¨uller 19.4.2016 22/60
  • 38. Was jeder Java-Entwickler ¨uber Strings wissen sollte Performanz Performanz: toString() Who Cares About toString Performance ? Blog von Antonio Goncalves [Gonc] Use Case: Großer Batch mit Logging und toString(), o.¨a. Effective Java [Joshua Bloch] Item 10: Always override toString toString()-Methode durch IDE generiert oder selbst gemacht mit Alternativen Null-Checks nicht vergessen Untersucht: JDK, Guava, CommonsLang3 Bernd M¨uller 19.4.2016 22/60
  • 39. Was jeder Java-Entwickler ¨uber Strings wissen sollte Performanz Performanz: toString() Who Cares About toString Performance ? Blog von Antonio Goncalves [Gonc] Use Case: Großer Batch mit Logging und toString(), o.¨a. Effective Java [Joshua Bloch] Item 10: Always override toString toString()-Methode durch IDE generiert oder selbst gemacht mit Alternativen Null-Checks nicht vergessen Untersucht: JDK, Guava, CommonsLang3 Gemessen: ” Average performance with Java Microbenchmarking Harness (ops/s)“ Bernd M¨uller 19.4.2016 22/60
  • 40. Was jeder Java-Entwickler ¨uber Strings wissen sollte Performanz Performanz: toString() Who Cares About toString Performance ? (cont’d) Ergebnisse Technic Average ops/s String concat with + 142.075,167 String builder 141.463,438 Objects.toString 140.791,365 Guava 110.111,808 ToStringBuilder (append) 75.165,552 ToStringBuilder (reflectionToString) 34.930,630 ReflectionToStringBuilder 23.204,479 Bernd M¨uller 19.4.2016 23/60
  • 41. Was jeder Java-Entwickler ¨uber Strings wissen sollte Performanz Performanz: toString() Who Cares About toString Performance? (cont’d) Zusammenfassung: ” Today with the JVM optimisation, we can safely use the + symbol to concatenate Strings (and use Objects.toString to handle nulls). With the utility class Objects that is built-in the JDK, no need to have external frameworks to deal with null values. So, out of the box, the JDK has better performance than any other technic described in this article.“ [Antonio Goncalves, Gonc] Bernd M¨uller 19.4.2016 24/60
  • 42. Was jeder Java-Entwickler ¨uber Strings wissen sollte Performanz Performanz: toString() Who Cares About toString Performance? (cont’d) Zusammenfassung: ” Today with the JVM optimisation, we can safely use the + symbol to concatenate Strings (and use Objects.toString to handle nulls). With the utility class Objects that is built-in the JDK, no need to have external frameworks to deal with null values. So, out of the box, the JDK has better performance than any other technic described in this article.“ [Antonio Goncalves, Gonc] Nachtrag: sowieso nur interessant, wenn Sie toString() sehr oft aufrufen Bernd M¨uller 19.4.2016 24/60
  • 43. Was jeder Java-Entwickler ¨uber Strings wissen sollte Performanz Performanz: String-Konkatenation Performanz: String-Konkatenation Bernd M¨uller 19.4.2016 25/60
  • 44. JDK String-Konkatenation @Benchmark // String + public static String concat () { String result = ; for (int i = 0; i IT; i++) { result += i; } return result; } @Benchmark // StringBuffer public static String concat () { StringBuffer builder = new Stri for (int i = 0; i IT; i++) { builder.append(i); } return builder.toString (); } @Benchmark // Joining Collector public static String concat () { return IntStream.range (0, IT) .mapToObj(String :: valueOf) .collect(Collectors.joining ()); } @Benchmark // StringBuilder public static String concat () { StringBuilder builder = new Str for (int i = 0; i IT; i++) { builder.append(i); } return builder.toString (); }
  • 45. Was jeder Java-Entwickler ¨uber Strings wissen sollte Performanz Performanz: String-Konkatenation JMH Ergebnisse Benchmark Score Error Units SC.concatWithJoiningCollector 2898,767 ± 5,378 ops/s SC.concatWithString 25,434 ± 0,059 ops/s SC.concatWithStringBuffer 5375,578 ± 39,959 ops/s SC.concatWithStringBuilder 6030,804 ± 13,088 ops/s Bernd M¨uller 19.4.2016 27/60
  • 46. Was jeder Java-Entwickler ¨uber Strings wissen sollte Internte Strings Internte Strings Bernd M¨uller 19.4.2016 28/60
  • 47. Was jeder Java-Entwickler ¨uber Strings wissen sollte Internte Strings Was ist das ? Internte Strings — Was ist das ? Bernd M¨uller 19.4.2016 29/60
  • 48. Was jeder Java-Entwickler ¨uber Strings wissen sollte Internte Strings Was ist das ? Internte Strings Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are ”interned” so as to share unique instances, using the method String.intern. [JLS 3.10.5 String Literals] Bernd M¨uller 19.4.2016 30/60
  • 49. Was jeder Java-Entwickler ¨uber Strings wissen sollte Internte Strings Was ist das ? Internte Strings Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are ”interned” so as to share unique instances, using the method String.intern. [JLS 3.10.5 String Literals] String-Memory-Pool mit allen internten Strings Bernd M¨uller 19.4.2016 30/60
  • 50. Was jeder Java-Entwickler ¨uber Strings wissen sollte Internte Strings Was ist das ? Internte Strings Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are ”interned” so as to share unique instances, using the method String.intern. [JLS 3.10.5 String Literals] String-Memory-Pool mit allen internten Strings Beim Laden einer Klasse in die VM wird gepr¨uft, ob String-Literal schon im Pool Bernd M¨uller 19.4.2016 30/60
  • 51. Was jeder Java-Entwickler ¨uber Strings wissen sollte Internte Strings Was ist das ? Internte Strings Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are ”interned” so as to share unique instances, using the method String.intern. [JLS 3.10.5 String Literals] String-Memory-Pool mit allen internten Strings Beim Laden einer Klasse in die VM wird gepr¨uft, ob String-Literal schon im Pool Falls ja, wird es wiederverwendet, falls nein, neu eingetragen Bernd M¨uller 19.4.2016 30/60
  • 52. Was jeder Java-Entwickler ¨uber Strings wissen sollte Internte Strings Was ist das ? Internte Strings Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are ”interned” so as to share unique instances, using the method String.intern. [JLS 3.10.5 String Literals] String-Memory-Pool mit allen internten Strings Beim Laden einer Klasse in die VM wird gepr¨uft, ob String-Literal schon im Pool Falls ja, wird es wiederverwendet, falls nein, neu eingetragen String-Literale gibt es also nur einmal in einer VM Bernd M¨uller 19.4.2016 30/60
  • 53. Was jeder Java-Entwickler ¨uber Strings wissen sollte Internte Strings Was ist das ? Internte String-Literale — Beispiele String str1 = Hello , World!; String str2 = Hello , World!; String str3 = new String(Hello , World!); // sinnlos Assert.assertSame(Hello , World!, Hello , World!); Assert.assertSame(str1 , str2 ); Assert.assertSame(Hel + lo, Hel + lo); Assert.assertNotSame(str1 + str1 , str2 + str2 ); Assert.assertEquals(str1 + str1 , str2 + str2 ); Assert.assertSame (( str1 + str1 ). intern (), (str2 + str2 ). intern ()); Assert.assertNotSame(str1 , str3 ); Bernd M¨uller 19.4.2016 31/60
  • 54. Was jeder Java-Entwickler ¨uber Strings wissen sollte Internte Strings Am¨usantes Am¨usantes Bernd M¨uller 19.4.2016 32/60
  • 55. Was jeder Java-Entwickler ¨uber Strings wissen sollte Internte Strings Am¨usantes Spielereien Was ist die Ausgabe? System.out.println(Hello , World!); magic (); System.out.println(Hello , World!); Bernd M¨uller 19.4.2016 33/60
  • 56. Was jeder Java-Entwickler ¨uber Strings wissen sollte Internte Strings Am¨usantes Spielereien Was ist die Ausgabe? System.out.println(Hello , World!); magic (); System.out.println(Hello , World!); private static void magic () throws Exception { Field field = String.class . getDeclaredField (value); field.setAccessible(true ); field.set(Hello , World!, tricky intern.toCharArray ()); } Zuerst gesehen bei Arno Haase Bernd M¨uller 19.4.2016 33/60
  • 57. Was jeder Java-Entwickler ¨uber Strings wissen sollte Internte Strings Am¨usantes Spielereien Was ist die Ausgabe? System.out.println(Hello , World!); magic (); System.out.println(Hello , World!); private static void magic () throws Exception { Field field = String.class . getDeclaredField (value); field.setAccessible(true ); field.set(Hello , World!, tricky intern.toCharArray ()); } Zuerst gesehen bei Arno Haase Bitte nicht nachmachen Bernd M¨uller 19.4.2016 33/60
  • 58. Was jeder Java-Entwickler ¨uber Strings wissen sollte Internte Strings Am¨usantes Spielereien (cont’d) Was ist die Ausgabe? System.out.println(Hello , World!); magic (); System.out.println(Hello , World!); public static void magic () throws Exception { Field field = String.class . getDeclaredField (value); field.setAccessible(true ); char [] chars = (char []) field.get(Hello World); System.arraycopy(tricky intern.toCharArray (), 0, chars , 0, chars.length ); } Bernd M¨uller 19.4.2016 34/60
  • 59. Was jeder Java-Entwickler ¨uber Strings wissen sollte Internte Strings Am¨usantes Spielereien (cont’d) Was ist die Ausgabe? System.out.println(Hello , World!); magic (); System.out.println(Hello , World!); public static void magic () throws Exception { Field field = String.class . getDeclaredField (value); field.setAccessible(true ); char [] chars = (char []) field.get(Hello World); System.arraycopy(tricky intern.toCharArray (), 0, chars , 0, chars.length ); } Ebenfalls nicht nachmachen Bernd M¨uller 19.4.2016 34/60
  • 60. Was jeder Java-Entwickler ¨uber Strings wissen sollte Internte Strings Nochmal Performanz Nochmal Performanz Bernd M¨uller 19.4.2016 35/60
  • 61. Was jeder Java-Entwickler ¨uber Strings wissen sollte Internte Strings Nochmal Performanz Java-Doc String.intern() Returns a canonical representation for the string object. A pool of strings, initially empty, is maintained privately by the class String. When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned. It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true. All literal strings and string-valued constant expressions are interned. String literals are defined in section 3.10.5 of the The JavaTM Language Specification. Returns: a string that has the same contents as this string, but is guaranteed to be from a pool of unique strings. Bernd M¨uller 19.4.2016 36/60
  • 62. Was jeder Java-Entwickler ¨uber Strings wissen sollte Internte Strings Nochmal Performanz Java-Doc String.intern() Returns a canonical representation for the string object. A pool of strings, initially empty, is maintained privately by the class String. When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned. It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true. All literal strings and string-valued constant expressions are interned. String literals are defined in section 3.10.5 of the The JavaTM Language Specification. Returns: a string that has the same contents as this string, but is guaranteed to be from a pool of unique strings. Bernd M¨uller 19.4.2016 36/60
  • 63. Was jeder Java-Entwickler ¨uber Strings wissen sollte Internte Strings Nochmal Performanz Java-Doc String.intern() Returns a canonical representation for the string object. A pool of strings, initially empty, is maintained privately by the class String. When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned. It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true. All literal strings and string-valued constant expressions are interned. String literals are defined in section 3.10.5 of the The JavaTM Language Specification. Returns: a string that has the same contents as this string, but is guaranteed to be from a pool of unique strings. Bernd M¨uller 19.4.2016 36/60
  • 64. Was jeder Java-Entwickler ¨uber Strings wissen sollte Internte Strings Nochmal Performanz Java-Doc String.intern() Returns a canonical representation for the string object. A pool of strings, initially empty, is maintained privately by the class String. When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned. It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true. All literal strings and string-valued constant expressions are interned. String literals are defined in section 3.10.5 of the The JavaTM Language Specification. Returns: a string that has the same contents as this string, but is guaranteed to be from a pool of unique strings. Bernd M¨uller 19.4.2016 36/60
  • 65. Was jeder Java-Entwickler ¨uber Strings wissen sollte Internte Strings Nochmal Performanz Java-Doc String.intern() Returns a canonical representation for the string object. A pool of strings, initially empty, is maintained privately by the class String. When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned. It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true. All literal strings and string-valued constant expressions are interned. String literals are defined in section 3.10.5 of the The JavaTM Language Specification. Returns: a string that has the same contents as this string, but is guaranteed to be from a pool of unique strings. Bernd M¨uller 19.4.2016 36/60
  • 66. Was jeder Java-Entwickler ¨uber Strings wissen sollte Internte Strings Nochmal Performanz Performanz-Idee: String-Interning und Equals ” On the topic of interning strings, what about using the intern() method to make the programm run faster, since interned strings can be compared via the == operator? That is a popular thought, though in most cases it turns out to by a myth. The String.equals() method is pretty fast. . . . Comparing strings via the == operator is undeniably faster, but the cost of interning the string must also be taken into consideration.“ [Java Performance, Scott Oaks] Bernd M¨uller 19.4.2016 37/60
  • 67. Was jeder Java-Entwickler ¨uber Strings wissen sollte Internte Strings Nochmal Performanz Performanz-Idee: String-Interning und Equals ” On the topic of interning strings, what about using the intern() method to make the programm run faster, since interned strings can be compared via the == operator? That is a popular thought, though in most cases it turns out to by a myth. The String.equals() method is pretty fast. . . . Comparing strings via the == operator is undeniably faster, but the cost of interning the string must also be taken into consideration.“ [Java Performance, Scott Oaks] Bernd M¨uller 19.4.2016 37/60
  • 68. Was jeder Java-Entwickler ¨uber Strings wissen sollte Internte Strings Nochmal Performanz Performanz-Idee: String-Interning und Equals ” On the topic of interning strings, what about using the intern() method to make the programm run faster, since interned strings can be compared via the == operator? That is a popular thought, though in most cases it turns out to by a myth. The String.equals() method is pretty fast. . . . Comparing strings via the == operator is undeniably faster, but the cost of interning the string must also be taken into consideration.“ [Java Performance, Scott Oaks] Bernd M¨uller 19.4.2016 37/60
  • 69. Was jeder Java-Entwickler ¨uber Strings wissen sollte Internte Strings Nochmal Performanz Performanz-Idee: String-Interning und Equals ” On the topic of interning strings, what about using the intern() method to make the programm run faster, since interned strings can be compared via the == operator? That is a popular thought, though in most cases it turns out to by a myth. The String.equals() method is pretty fast. . . . Comparing strings via the == operator is undeniably faster, but the cost of interning the string must also be taken into consideration.“ [Java Performance, Scott Oaks] Bernd M¨uller 19.4.2016 37/60
  • 70. Was jeder Java-Entwickler ¨uber Strings wissen sollte Internte Strings Nochmal Performanz Java Performance, Scott Oaks ” Like most optimizations, interning strings shouldn’t be done arbitrarily, but it can be effective if there are lots of duplicate strings occupying a significant portion of the heap.“ Bernd M¨uller 19.4.2016 38/60
  • 71. Was jeder Java-Entwickler ¨uber Strings wissen sollte Internte Strings Und nochmal Performanz Und nochmal Performanz Bernd M¨uller 19.4.2016 39/60
  • 72. Was jeder Java-Entwickler ¨uber Strings wissen sollte Internte Strings Und nochmal Performanz Auch bitte nicht selbst versuchen: MyString ” In compiler theory, an intrinsic function is a function available for use in a given programming language whose implementation is handled specially by the compiler. Typically, it substitutes a sequence of automatically generated instructions for the original function call, similar to an inline function. Unlike an inline function though, the compiler has an intimate knowledge of the intrinsic function and can therefore better integrate it and optimize it for the situation.“[Wikipedia,Intr1] Bernd M¨uller 19.4.2016 40/60
  • 73. Was jeder Java-Entwickler ¨uber Strings wissen sollte Internte Strings Und nochmal Performanz Auch bitte nicht selbst versuchen: MyString ” In compiler theory, an intrinsic function is a function available for use in a given programming language whose implementation is handled specially by the compiler. Typically, it substitutes a sequence of automatically generated instructions for the original function call, similar to an inline function. Unlike an inline function though, the compiler has an intimate knowledge of the intrinsic function and can therefore better integrate it and optimize it for the situation.“[Wikipedia,Intr1] Bernd M¨uller 19.4.2016 40/60
  • 74. Was jeder Java-Entwickler ¨uber Strings wissen sollte Internte Strings Und nochmal Performanz Auch bitte nicht selbst versuchen: MyString ” In compiler theory, an intrinsic function is a function available for use in a given programming language whose implementation is handled specially by the compiler. Typically, it substitutes a sequence of automatically generated instructions for the original function call, similar to an inline function. Unlike an inline function though, the compiler has an intimate knowledge of the intrinsic function and can therefore better integrate it and optimize it for the situation.“[Wikipedia,Intr1] Bernd M¨uller 19.4.2016 40/60
  • 75. Was jeder Java-Entwickler ¨uber Strings wissen sollte Internte Strings Und nochmal Performanz Auch bitte nicht selbst versuchen: MyString ” In compiler theory, an intrinsic function is a function available for use in a given programming language whose implementation is handled specially by the compiler. Typically, it substitutes a sequence of automatically generated instructions for the original function call, similar to an inline function. Unlike an inline function though, the compiler has an intimate knowledge of the intrinsic function and can therefore better integrate it and optimize it for the situation.“[Wikipedia,Intr1] In Java Compiler, JIT, evtl. sogar in JVM eingebaut Bernd M¨uller 19.4.2016 40/60
  • 76. Was jeder Java-Entwickler ¨uber Strings wissen sollte Internte Strings Und nochmal Performanz Auch bitte nicht selbst versuchen: MyString ” In compiler theory, an intrinsic function is a function available for use in a given programming language whose implementation is handled specially by the compiler. Typically, it substitutes a sequence of automatically generated instructions for the original function call, similar to an inline function. Unlike an inline function though, the compiler has an intimate knowledge of the intrinsic function and can therefore better integrate it and optimize it for the situation.“[Wikipedia,Intr1] In Java Compiler, JIT, evtl. sogar in JVM eingebaut String.equals() ist intrinsic. String.indexOf(), String.compareTo() ebenfalls [Krystal Mo,Intr2] String.intern() ist sogar nativ implementiert Bernd M¨uller 19.4.2016 40/60
  • 77. Was jeder Java-Entwickler ¨uber Strings wissen sollte Internte Strings Implementierung Implementierung Bernd M¨uller 19.4.2016 41/60
  • 78. Was jeder Java-Entwickler ¨uber Strings wissen sollte Internte Strings Implementierung Der String-Pool Implementiert als Hashtable fester Gr¨oße Bernd M¨uller 19.4.2016 42/60
  • 79. Was jeder Java-Entwickler ¨uber Strings wissen sollte Internte Strings Implementierung Der String-Pool Implementiert als Hashtable fester Gr¨oße Bucket-Gr¨oße ab Java 6 einstellbar Bernd M¨uller 19.4.2016 42/60
  • 80. Was jeder Java-Entwickler ¨uber Strings wissen sollte Internte Strings Implementierung Der String-Pool Implementiert als Hashtable fester Gr¨oße Bucket-Gr¨oße ab Java 6 einstellbar Nativ in JVM realisiert, Gr¨oße nicht ver¨anderbar Bernd M¨uller 19.4.2016 42/60
  • 81. Was jeder Java-Entwickler ¨uber Strings wissen sollte Internte Strings Implementierung Der String-Pool Implementiert als Hashtable fester Gr¨oße Bucket-Gr¨oße ab Java 6 einstellbar Nativ in JVM realisiert, Gr¨oße nicht ver¨anderbar In Java 6 in Permanent Generation, 7 und h¨oher im Heap Bernd M¨uller 19.4.2016 42/60
  • 82. Was jeder Java-Entwickler ¨uber Strings wissen sollte Internte Strings Implementierung Der String-Pool Implementiert als Hashtable fester Gr¨oße Bucket-Gr¨oße ab Java 6 einstellbar Nativ in JVM realisiert, Gr¨oße nicht ver¨anderbar In Java 6 in Permanent Generation, 7 und h¨oher im Heap Daher in Java 6 OOME: PermGen space Bernd M¨uller 19.4.2016 42/60
  • 83. Was jeder Java-Entwickler ¨uber Strings wissen sollte Internte Strings Implementierung Der String-Pool Implementiert als Hashtable fester Gr¨oße Bucket-Gr¨oße ab Java 6 einstellbar Nativ in JVM realisiert, Gr¨oße nicht ver¨anderbar In Java 6 in Permanent Generation, 7 und h¨oher im Heap Daher in Java 6 OOME: PermGen space Java 7 und h¨oher OOME: Java heap space Bernd M¨uller 19.4.2016 42/60
  • 84. Was jeder Java-Entwickler ¨uber Strings wissen sollte Internte Strings Implementierung Der String-Pool Implementiert als Hashtable fester Gr¨oße Bucket-Gr¨oße ab Java 6 einstellbar Nativ in JVM realisiert, Gr¨oße nicht ver¨anderbar In Java 6 in Permanent Generation, 7 und h¨oher im Heap Daher in Java 6 OOME: PermGen space Java 7 und h¨oher OOME: Java heap space Gr¨oßen: Bernd M¨uller 19.4.2016 42/60
  • 85. Was jeder Java-Entwickler ¨uber Strings wissen sollte Internte Strings Implementierung Der String-Pool Implementiert als Hashtable fester Gr¨oße Bucket-Gr¨oße ab Java 6 einstellbar Nativ in JVM realisiert, Gr¨oße nicht ver¨anderbar In Java 6 in Permanent Generation, 7 und h¨oher im Heap Daher in Java 6 OOME: PermGen space Java 7 und h¨oher OOME: Java heap space Gr¨oßen: Vor Java 7u40 1009 Buckets Bernd M¨uller 19.4.2016 42/60
  • 86. Was jeder Java-Entwickler ¨uber Strings wissen sollte Internte Strings Implementierung Der String-Pool Implementiert als Hashtable fester Gr¨oße Bucket-Gr¨oße ab Java 6 einstellbar Nativ in JVM realisiert, Gr¨oße nicht ver¨anderbar In Java 6 in Permanent Generation, 7 und h¨oher im Heap Daher in Java 6 OOME: PermGen space Java 7 und h¨oher OOME: Java heap space Gr¨oßen: Vor Java 7u40 1009 Buckets Java 7u40 und sp¨ater 60013 Bernd M¨uller 19.4.2016 42/60
  • 87. Was jeder Java-Entwickler ¨uber Strings wissen sollte Internte Strings Implementierung Der String-Pool Implementiert als Hashtable fester Gr¨oße Bucket-Gr¨oße ab Java 6 einstellbar Nativ in JVM realisiert, Gr¨oße nicht ver¨anderbar In Java 6 in Permanent Generation, 7 und h¨oher im Heap Daher in Java 6 OOME: PermGen space Java 7 und h¨oher OOME: Java heap space Gr¨oßen: Vor Java 7u40 1009 Buckets Java 7u40 und sp¨ater 60013 VM-Schalter: Bernd M¨uller 19.4.2016 42/60
  • 88. Was jeder Java-Entwickler ¨uber Strings wissen sollte Internte Strings Implementierung Der String-Pool Implementiert als Hashtable fester Gr¨oße Bucket-Gr¨oße ab Java 6 einstellbar Nativ in JVM realisiert, Gr¨oße nicht ver¨anderbar In Java 6 in Permanent Generation, 7 und h¨oher im Heap Daher in Java 6 OOME: PermGen space Java 7 und h¨oher OOME: Java heap space Gr¨oßen: Vor Java 7u40 1009 Buckets Java 7u40 und sp¨ater 60013 VM-Schalter: -XX:StringTableSize=value Bernd M¨uller 19.4.2016 42/60
  • 89. Was jeder Java-Entwickler ¨uber Strings wissen sollte Internte Strings Implementierung Der String-Pool Implementiert als Hashtable fester Gr¨oße Bucket-Gr¨oße ab Java 6 einstellbar Nativ in JVM realisiert, Gr¨oße nicht ver¨anderbar In Java 6 in Permanent Generation, 7 und h¨oher im Heap Daher in Java 6 OOME: PermGen space Java 7 und h¨oher OOME: Java heap space Gr¨oßen: Vor Java 7u40 1009 Buckets Java 7u40 und sp¨ater 60013 VM-Schalter: -XX:StringTableSize=value -XX:+PrintStringTableStatistics (Java 7u6 und gr¨oßer, 6u32 Backport) Bernd M¨uller 19.4.2016 42/60
  • 90. Beispiele -XX:+PrintStringTableStatistics StringTable statistics: Number of buckets : 1003 Average bucket size : 33 Variance of bucket size : 33 Std. dev. of bucket size: 6 Maximum bucket size : 51
  • 91. Beispiele -XX:+PrintStringTableStatistics StringTable statistics: Number of buckets : 1003 Average bucket size : 33 Variance of bucket size : 33 Std. dev. of bucket size: 6 Maximum bucket size : 51
  • 92. Beispiele -XX:+PrintStringTableStatistics StringTable statistics: Number of buckets : 1003 Average bucket size : 33 Variance of bucket size : 33 Std. dev. of bucket size: 6 Maximum bucket size : 51 Schlecht StringTable statistics: Number of buckets : 60013 Average bucket size : 1 Variance of bucket size : 1 Std. dev. of bucket size: 1 Maximum bucket size : 10
  • 93. Beispiele -XX:+PrintStringTableStatistics StringTable statistics: Number of buckets : 1003 Average bucket size : 33 Variance of bucket size : 33 Std. dev. of bucket size: 6 Maximum bucket size : 51 Schlecht StringTable statistics: Number of buckets : 60013 Average bucket size : 1 Variance of bucket size : 1 Std. dev. of bucket size: 1 Maximum bucket size : 10
  • 94. Beispiele -XX:+PrintStringTableStatistics StringTable statistics: Number of buckets : 1003 Average bucket size : 33 Variance of bucket size : 33 Std. dev. of bucket size: 6 Maximum bucket size : 51 Schlecht StringTable statistics: Number of buckets : 60013 Average bucket size : 1 Variance of bucket size : 1 Std. dev. of bucket size: 1 Maximum bucket size : 10Viel besser StringTable statistics: Number of buckets : 60013 Average bucket size : 0 Variance of bucket size : 0 Std. dev. of bucket size: 1 Maximum bucket size : 5
  • 95. Beispiele -XX:+PrintStringTableStatistics StringTable statistics: Number of buckets : 1003 Average bucket size : 33 Variance of bucket size : 33 Std. dev. of bucket size: 6 Maximum bucket size : 51 Schlecht StringTable statistics: Number of buckets : 60013 Average bucket size : 1 Variance of bucket size : 1 Std. dev. of bucket size: 1 Maximum bucket size : 10Viel besser StringTable statistics: Number of buckets : 60013 Average bucket size : 0 Variance of bucket size : 0 Std. dev. of bucket size: 1 Maximum bucket size : 5
  • 96. Beispiele -XX:+PrintStringTableStatistics StringTable statistics: Number of buckets : 1003 Average bucket size : 33 Variance of bucket size : 33 Std. dev. of bucket size: 6 Maximum bucket size : 51 Schlecht StringTable statistics: Number of buckets : 60013 Average bucket size : 1 Variance of bucket size : 1 Std. dev. of bucket size: 1 Maximum bucket size : 10Viel besser StringTable statistics: Number of buckets : 60013 Average bucket size : 0 Variance of bucket size : 0 Std. dev. of bucket size: 1 Maximum bucket size : 5 Empfehlenswert
  • 97. In Java 8 ausf¨uhrlichere Informationen StringTable statistics: Number of buckets : 60013 = 480104 bytes , avg 8,000 Number of entries : 797 = 19128 bytes , avg 24 ,000 Number of literals : 797 = 151960 bytes , avg 190 ,665 Total footprint : = 651192 bytes Average bucket size : 0,013 Variance of bucket size : 0,013 Std. dev. of bucket size: 0,115 Maximum bucket size : 2
  • 98. Was jeder Java-Entwickler ¨uber Strings wissen sollte GC1 String-Deduplication GC1 + JVM-Optionen Bernd M¨uller 19.4.2016 45/60
  • 99. JEP 192: String Deduplication in G1 [JEP192] Summary ” Reduce the Java heap live-data set by enhancing the G1 garbage collector so that duplicate instances of String are automatically and continuously deduplicated. “
  • 100. JEP 192: String Deduplication in G1 [JEP192] Summary ” Reduce the Java heap live-data set by enhancing the G1 garbage collector so that duplicate instances of String are automatically and continuously deduplicated. “ Motivation ” . . . Measurements have shown that roughly 25% of the Java heap live data set in these types of applications is consumed by String objects. . . . roughly half of those String objects are duplicates . . . Having duplicate String objects on the heap is, essentially, just a waste of memory“
  • 101. JEP 192: String Deduplication in G1 [JEP192] Summary ” Reduce the Java heap live-data set by enhancing the G1 garbage collector so that duplicate instances of String are automatically and continuously deduplicated. “ Motivation ” . . . Measurements have shown that roughly 25% of the Java heap live data set in these types of applications is consumed by String objects. . . . roughly half of those String objects are duplicates . . . Having duplicate String objects on the heap is, essentially, just a waste of memory“ Description ” The value field is implementation-specific and not observable from outside . . . This means that it can safely and transparently be used by multiple instances of String at the same time.
  • 102. JEP 192: String Deduplication in G1 [JEP192] Summary ” Reduce the Java heap live-data set by enhancing the G1 garbage collector so that duplicate instances of String are automatically and continuously deduplicated. “ Motivation ” . . . Measurements have shown that roughly 25% of the Java heap live data set in these types of applications is consumed by String objects. . . . roughly half of those String objects are duplicates . . . Having duplicate String objects on the heap is, essentially, just a waste of memory“ Description ” The value field is implementation-specific and not observable from outside . . . This means that it can safely and transparently be used by multiple instances of String at the same time. Deduplicating a String object is conceptually just an re-assignment of the value field, i.e., aString.value = anotherString.value.
  • 103. -XX:+UseG1GC -XX:+UseStringDeduplication String tmp = some string; String string1 = new String(tmp + tmp); String string2 = new String(tmp + tmp); Field field = String.class. getDeclaredField (value); field.setAccessible(true ); Assert.assertEquals(string1 , string2 ); Assert.assertNotSame(string1 , string2 ); Assert.assertNotSame(field.get(string1), field.get(string2 )); System.gc(); Thread.sleep (1000); Assert.assertNotSame(string1 , string2 ); Assert.assertSame(field.get(string1), field.get(string2 ));
  • 104. Was jeder Java-Entwickler ¨uber Strings wissen sollte GC1 String-Deduplication Erfahrungsbericht Artikel G1: from garbage collector to waste management consultant von Erik Costlow, 24.3.2016, Java Platform Group, Product Management blog Aussage: String Deduplication may decrease heap usage by about 10% Am Beispiel Eclipse Referenz: [DEDUP] Bernd M¨uller 19.4.2016 48/60
  • 105. Was jeder Java-Entwickler ¨uber Strings wissen sollte Dies und das Dies und das Bernd M¨uller 19.4.2016 49/60
  • 106. Was jeder Java-Entwickler ¨uber Strings wissen sollte Dies und das Heinz Kabutz, Reflection Madness, JAX London 2014 Java 1.0 - 1.2 String contained char[], offset, count Java 1.3 - 1.6 Added a cached hash code String became a shared, mutable, but thread-safe class Java 1.7 Got rid of offset and length and added hash32 Java 1.8 Got rid of hash32 again Bernd M¨uller 19.4.2016 50/60
  • 107. Was jeder Java-Entwickler ¨uber Strings wissen sollte Dies und das Andere String-relevante VM-Optionen -XX:+UseStringCache ” Enables caching of commonly allocated strings.“ Keine weiteren Informationen gefunden. Vorhanden in Java 6 und 7. Entfernt in Java 8 Bernd M¨uller 19.4.2016 51/60
  • 108. Was jeder Java-Entwickler ¨uber Strings wissen sollte Dies und das Andere String-relevante VM-Optionen -XX:+UseStringCache ” Enables caching of commonly allocated strings.“ Keine weiteren Informationen gefunden. Vorhanden in Java 6 und 7. Entfernt in Java 8 -XX:+UseCompressedStrings ” Use a byte[] for Strings which can be represented as pure ASCII.“ Eingef¨uhrt in Java 6u21. Wieder entfernt in Java 7 Bernd M¨uller 19.4.2016 51/60
  • 109. Was jeder Java-Entwickler ¨uber Strings wissen sollte Dies und das Andere String-relevante VM-Optionen -XX:+UseStringCache ” Enables caching of commonly allocated strings.“ Keine weiteren Informationen gefunden. Vorhanden in Java 6 und 7. Entfernt in Java 8 -XX:+UseCompressedStrings ” Use a byte[] for Strings which can be represented as pure ASCII.“ Eingef¨uhrt in Java 6u21. Wieder entfernt in Java 7 -XX:+OptimizeStringConcat ” Optimize String concatenation operations where possible.“ Eingef¨uhrt in Java 6u20. Optimiert wiederholte StringBuilder append()-Aufrufe Bernd M¨uller 19.4.2016 51/60
  • 110. Was jeder Java-Entwickler ¨uber Strings wissen sollte Dies und das Ausblick — es geht immer weiter . . . JEP 254: Compact Strings [JEP254] Bernd M¨uller 19.4.2016 52/60
  • 111. Was jeder Java-Entwickler ¨uber Strings wissen sollte Dies und das Ausblick — es geht immer weiter . . . JEP 254: Compact Strings [JEP254] Bereits 8/2014 definiert Bernd M¨uller 19.4.2016 52/60
  • 112. Was jeder Java-Entwickler ¨uber Strings wissen sollte Dies und das Ausblick — es geht immer weiter . . . JEP 254: Compact Strings [JEP254] Bereits 8/2014 definiert ” Wiederbelebung“ von -XX:+UseCompressedStrings Bernd M¨uller 19.4.2016 52/60
  • 113. Was jeder Java-Entwickler ¨uber Strings wissen sollte Dies und das Ausblick — es geht immer weiter . . . JEP 254: Compact Strings [JEP254] Bereits 8/2014 definiert ” Wiederbelebung“ von -XX:+UseCompressedStrings kodiert Zeichen als ISO-8859-1/Latin-1 (1 Byte pro Zeichen) oder UTF-16 (2 Bytes pro Zeichen) Bernd M¨uller 19.4.2016 52/60
  • 114. Was jeder Java-Entwickler ¨uber Strings wissen sollte Dies und das Ausblick — es geht immer weiter . . . JEP 254: Compact Strings [JEP254] Bereits 8/2014 definiert ” Wiederbelebung“ von -XX:+UseCompressedStrings kodiert Zeichen als ISO-8859-1/Latin-1 (1 Byte pro Zeichen) oder UTF-16 (2 Bytes pro Zeichen) Marker zur Kennzeichnung Bernd M¨uller 19.4.2016 52/60
  • 115. Was jeder Java-Entwickler ¨uber Strings wissen sollte Dies und das Ausblick — es geht immer weiter . . . JEP 254: Compact Strings [JEP254] Bereits 8/2014 definiert ” Wiederbelebung“ von -XX:+UseCompressedStrings kodiert Zeichen als ISO-8859-1/Latin-1 (1 Byte pro Zeichen) oder UTF-16 (2 Bytes pro Zeichen) Marker zur Kennzeichnung JavaOne 2015, CON5483: Compact Strings: A Memory-Efficient Internal Representation for Strings Bernd M¨uller 19.4.2016 52/60
  • 116. Was jeder Java-Entwickler ¨uber Strings wissen sollte Dies und das Ausblick — es geht immer weiter . . . JEP 254: Compact Strings [JEP254] Bereits 8/2014 definiert ” Wiederbelebung“ von -XX:+UseCompressedStrings kodiert Zeichen als ISO-8859-1/Latin-1 (1 Byte pro Zeichen) oder UTF-16 (2 Bytes pro Zeichen) Marker zur Kennzeichnung JavaOne 2015, CON5483: Compact Strings: A Memory-Efficient Internal Representation for Strings Gemeinsames Projekt von Oracle und Intel, 10+ Entwickler Bernd M¨uller 19.4.2016 52/60
  • 117. Was jeder Java-Entwickler ¨uber Strings wissen sollte Dies und das Ausblick — es geht immer weiter . . . JEP 254: Compact Strings [JEP254] Bereits 8/2014 definiert ” Wiederbelebung“ von -XX:+UseCompressedStrings kodiert Zeichen als ISO-8859-1/Latin-1 (1 Byte pro Zeichen) oder UTF-16 (2 Bytes pro Zeichen) Marker zur Kennzeichnung JavaOne 2015, CON5483: Compact Strings: A Memory-Efficient Internal Representation for Strings Gemeinsames Projekt von Oracle und Intel, 10+ Entwickler Kommt in Java 9. In neueren EAs enthalten Bernd M¨uller 19.4.2016 52/60
  • 118. Was jeder Java-Entwickler ¨uber Strings wissen sollte Dies und das Wer an Schnittstellen vorbei programmiert, ist selbst schuld . . . Große Diskussion: sun.misc.Unsafe Bernd M¨uller 19.4.2016 53/60
  • 119. Was jeder Java-Entwickler ¨uber Strings wissen sollte Dies und das Wer an Schnittstellen vorbei programmiert, ist selbst schuld . . . Große Diskussion: sun.misc.Unsafe Hier: magic(), in Abschnitt Am¨usantes Bernd M¨uller 19.4.2016 53/60
  • 120. Was jeder Java-Entwickler ¨uber Strings wissen sollte Dies und das Wer an Schnittstellen vorbei programmiert, ist selbst schuld . . . Große Diskussion: sun.misc.Unsafe Hier: magic(), in Abschnitt Am¨usantes . . . schauen wir uns die Details an . . . Bernd M¨uller 19.4.2016 53/60
  • 121. Was jeder Java-Entwickler ¨uber Strings wissen sollte Dies und das String-Interna vor JEP 254 /** The value is used for character storage. */ private final char value []; Bernd M¨uller 19.4.2016 54/60
  • 122. String-Interna nach JEP 254 /** * The value is used for character storage . * * @implNote This field is trusted by the VM , and is a subject to * constant folding if String instance is constant . Overwriting this * field after construction will cause problems . * * Additionally , it is marked with { @link Stable } to trust the contents * of the array. No other facility in JDK provides this functionality (yet ). * {@link Stable } is safe here , because value is never null. */ @Stable private final byte [] value; /** * The identifier of the encoding used to encode the bytes in * {@code value }. The supported values in this implementation are * * LATIN1 * UTF16 * * @implNote This field is trusted by the VM , and is a subject to * constant folding if String instance is constant . Overwriting this * field after construction will cause problems . */ private final byte coder;
  • 123. Was jeder Java-Entwickler ¨uber Strings wissen sollte Dies und das magic() ¨uberarbeitet Wirft mit Java 9 Exception: java.lang. IllegalArgumentException : Can not set final [B field java.lang.String.value to [C Bernd M¨uller 19.4.2016 56/60
  • 124. Was jeder Java-Entwickler ¨uber Strings wissen sollte Dies und das magic() ¨uberarbeitet Wirft mit Java 9 Exception: java.lang. IllegalArgumentException : Can not set final [B field java.lang.String.value to [C ¨Uberarbeitung: aus private static void magic () throws Exception { Field field = String.class. getDeclaredField (value); field. setAccessible (true ); field.set(Hello , World!, tricky intern.toCharArray ()); } wird private static void magic () throws Exception { Field field = String.class. getDeclaredField (value); field. setAccessible (true ); field.set(Hello , World!, tricky intern.getBytes ()); } Bernd M¨uller 19.4.2016 56/60
  • 125. Was jeder Java-Entwickler ¨uber Strings wissen sollte Fragen und Anmerkungen Fragen und Anmerkungen Bernd M¨uller 19.4.2016 57/60
  • 126. Was jeder Java-Entwickler ¨uber Strings wissen sollte Referenzen Referenzen Bernd M¨uller 19.4.2016 58/60
  • 127. Was jeder Java-Entwickler ¨uber Strings wissen sollte Referenzen Referenzen [Gonc] Antonio Goncalves: Who Cares About toString Performance? [Intr1] Wikipedia: Intrinsic function [Intr2] Krystal Mo. Intrinsic Methods in HotSpot VM [Bug1] JDK-6962931: move interned strings out of the perm gen [Bug2] JDK-6964458: Reimplement class meta-data storage to use native memory [Bug3] JDK-4513622: (str) keeping a substring of a field prevents GC for object [JEP192] JEP 192: String Deduplication in G1 [JEP254] JEP 254: Compact Strings [DEDUP] G1: from garbage collector to waste management consultant Bernd M¨uller 19.4.2016 59/60
  • 128. Was jeder Java-Entwickler ¨uber Strings wissen sollte Referenzen Referenzen (cont’d) [CHAR1] Supplementary Characters in the Java Platform [CHAR2] Supplementary Characters as Surrogates [CHAR3] Unicode Character Representations [CHAR4] Supported Encodings [CHAR5] Unicode 4.0 support in J2SE 1.5 Bernd M¨uller 19.4.2016 60/60