In some programs, we have a choice in how to call String.join—we can change code to use an array or avoid arrays. String.join can handle either case.
public class Program {
public static void main(String[] args) {
String value1 =
"cat";
String value2 =
"dog";
String value3 =
"elephant";
String[] array = new String[3];
array[0] =
"cat";
array[1] =
"dog";
array[2] =
"elephant";
long t1 = System.currentTimeMillis();
// Version 1: pass separate string arguments.
for (int i = 0; i < 10000000; i++) {
String result = String.join(
":", value1, value2, value3);
if (result.length() == 0) {
System.out.println(0);
}
}
long t2 = System.currentTimeMillis();
// Version 2: pass array of Strings.
for (int i = 0; i < 10000000; i++) {
String result = String.join(
":", array);
if (result.length() == 0) {
System.out.println(0);
}
}
long t3 = System.currentTimeMillis();
// ... Result times.
System.out.println(t2 - t1);
System.out.println(t3 - t2);
}
}
1104 ms: 3 Strings
934 ms: String array