Skip to content

Instantly share code, notes, and snippets.

@mattantonelli
Created September 16, 2014 13:28
Show Gist options
  • Save mattantonelli/9a48d039fb78de653d3b to your computer and use it in GitHub Desktop.
Save mattantonelli/9a48d039fb78de653d3b to your computer and use it in GitHub Desktop.
Comparing the time to convert a List to an Array versus remaining as an Array.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TestListToArrayConversion {
public static void main(String[] args) {
Map<String, Object> testMap = new HashMap<String, Object>();
List<TestString> testStrs = new ArrayList<TestString>();
for(int i = 0; i < 10; i++) {
testStrs.add(new TestString());
}
long startTime = System.nanoTime();
for(long i = 0; i < 100000000; i++) {
testMap.put("TestArray", getTestArray(testStrs));
}
System.out.println("Array: " + (System.nanoTime() - startTime));
startTime = System.nanoTime();
for(long i = 0; i < 100000000; i++) {
testMap.put("TestList", getTestList(testStrs));
}
System.out.println("List: " + (System.nanoTime() - startTime));
}
private static List<String> getTestList(List<TestString> strings) {
List<String> testList = new ArrayList<String>();
for(TestString testStr : strings) {
testList.add(testStr.getString());
}
return testList;
}
private static String[] getTestArray(List<TestString> strings) {
List<String> testList = new ArrayList<String>();
for(TestString testStr : strings) {
testList.add(testStr.getString());
}
return testList.toArray(new String[testList.size()]);
}
private static class TestString {
private final String str;
public TestString() {
this.str = "test";
}
public String getString() {
return str;
}
}
}
/**
* Array: 14384976374
* List: 10540872310
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment