Created
February 20, 2014 13:51
-
-
Save jbrisbin/9114012 to your computer and use it in GitHub Desktop.
Array vs List iteration throughput test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ArrayVsListThroughputTests { | |
static long TIMEOUT = 5000; | |
@Test | |
public void testArrayVsListIteration() { | |
int items = 10; | |
String[] strArray = new String[items]; | |
List<String> strList = new ArrayList<String>(); | |
for(int i = 0; i < items; i++) { | |
strArray[i] = "Hello World!"; | |
strList.add("Hello World!"); | |
} | |
doIterationTest("list", strList); | |
doIterationTest("array", strArray); | |
doArrayIterationTest(strArray); | |
} | |
private void doIterationTest(String type, Object obj) { | |
boolean isArray = obj.getClass().isArray(); | |
long start = System.currentTimeMillis(); | |
while(System.currentTimeMillis() - start < TIMEOUT) { | |
if(isArray) { | |
for(Object o : (Object[])obj) { | |
counter.incrementAndGet(); | |
} | |
} else { | |
for(Object o : (Iterable<?>)obj) { | |
counter.incrementAndGet(); | |
} | |
} | |
} | |
long end = System.currentTimeMillis(); | |
double elapsed = end - start; | |
System.out.format("%s iterator throughput %s/sec in %sms%n", | |
type, | |
(counter.get() / (int)(elapsed / 1000)), | |
(int)elapsed); | |
} | |
private void doArrayIterationTest(Object[] array) { | |
Map<Long, Object[]> arrayCache = new HashMap<Long, Object[]>(); | |
long threadId = (int)Thread.currentThread().getId(); | |
int len = array.length; | |
Object[] newArray = new Object[len]; | |
System.arraycopy(array, 0, newArray, 0, len); | |
arrayCache.put(threadId, newArray); | |
long start = System.currentTimeMillis(); | |
while(System.currentTimeMillis() - start < TIMEOUT) { | |
Object[] objs = arrayCache.get(threadId); | |
for(int i = 0; i < len; i++) { | |
Object o = objs[i]; | |
counter.incrementAndGet(); | |
} | |
} | |
long end = System.currentTimeMillis(); | |
double elapsed = end - start; | |
System.out.format("array for throughput %s/sec in %sms%n", | |
(counter.get() / (int)(elapsed / 1000)), | |
(int)elapsed); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment