Java Example – String optimization
The following example demonstrates optimizing strings with the String.intern() method:
StringOptimization.java file
public
class
StringOptimization
{
public
static
void
main
(
String
[
]
args
)
{
String
variables
[
]
=
new
String
[
50000
]
;
for
(
int
i
=
0
;
i
<
50000
;
i
++
)
{
variables
[
i
]
=
"
s
"
i
;
}
long
startTime0
=
System
.
currentTimeMillis
(
)
;
for
(
int
i
=
0
;
i
<
50000
;
i
++
)
{
variables
[
i
]
=
"
hello
"
;
}
long
endTime0
=
System
.
currentTimeMillis
(
)
;
System
.
out
.
println
(
"
Using the string directly:
"
(
endTime0
startTime0
)
"
ms
"
)
;
long
startTime1
=
System
.
currentTimeMillis
(
)
;
for
(
int
i
=
0
;
i
<
50000
;
i
++
)
{
variables
[
i
]
=
new
String
(
"
hello
"
)
;
}
long
endTime1
=
System
.
currentTimeMillis
(
)
;
System
.
out
.
println
(
"
Using the new keyword:
"
(
endTime1
startTime1
)
"
ms
"
)
;
long
startTime2
=
System
.
currentTimeMillis
(
)
;
for
(
int
i
=
0
;
i
<
50000
;
i
++
)
{
variables
[
i
]
=
new
String
(
"
hello
"
)
;
variables
[
i
]
=
variables
[
i
]
.
intern
(
)
;
}
long
endTime2
=
System
.
currentTimeMillis
(
)
;
System
.
out
.
println
(
"
Using the intern() method of the string object:
"
(
endTime2
startTime2
)
"
ms
"
)
;
}
}
The output of the above code example is:
直接使用字符串: 3 ms
使用 new 关键字:5 ms
使用字符串对象的 intern() 方法: 10 ms
Java Examples