Java Example – String performance comparison test
The following example demonstrates creating strings in two ways and tests their performance:
StringComparePerformance.java file
public
class
StringComparePerformance
{
public
static
void
main
(
String
[
]
args
)
{
long
startTime
=
System
.
currentTimeMillis
(
)
;
for
(
int
i
=
0
;
i
<
50000
;
i
++
)
{
String
s1
=
"
hello
"
;
String
s2
=
"
hello
"
;
}
long
endTime
=
System
.
currentTimeMillis
(
)
;
System
.
out
.
println
(
"
Creating a string with the String keyword
"
"
:
"
(
endTime
startTime
)
"
Millisecond
"
)
;
long
startTime1
=
System
.
currentTimeMillis
(
)
;
for
(
int
i
=
0
;
i
<
50000
;
i
++
)
{
String
s3
=
new
String
(
"
hello
"
)
;
String
s4
=
new
String
(
"
hello
"
)
;
}
long
endTime1
=
System
.
currentTimeMillis
(
)
;
System
.
out
.
println
(
"
Creating a string via a String object
"
"
:
"
(
endTime1
startTime1
)
"
Millisecond
"
)
;
}
}
The output of the above code example is:
通过 String 关键词创建字符串 : 6 毫秒
通过 String 对象创建字符串 : 14 毫秒
Java Examples