Java benchmark
import org.junit.Test; | |
import java.util.Arrays; | |
import java.util.Objects; | |
import static org.assertj.core.api.Assertions.*; | |
public class BenchmarkTests { | |
static class Record implements Comparable<Record> { | |
private final String textField; | |
private final double numericField; | |
public Record(String textField, double numericField) { | |
this.textField = textField; | |
this.numericField = numericField; | |
} | |
@Override | |
public boolean equals(Object o) { | |
if (this == o) return true; | |
if (!(o instanceof Record)) return false; | |
Record record = (Record) o; | |
return numericField == record.numericField && | |
Objects.equals(textField, record.textField); | |
} | |
@Override | |
public int hashCode() { | |
return Objects.hash(textField, numericField); | |
} | |
@Override | |
public int compareTo(Record record) { | |
return Double.compare(record.numericField, this.numericField); | |
} | |
} | |
@Test | |
public void it_iterates_very_fast_my_friend (){ | |
int arraySize = 10000; | |
Record[] items = createArray(arraySize); | |
long timeBefore = System.currentTimeMillis(); | |
exploreItems(items); // iteration | |
long timeAfter = System.currentTimeMillis(); | |
assertThat(timeAfter - timeBefore).isLessThan(5); | |
// 1ms on my i7 | |
} | |
@Test | |
public void it_sorts_very_fast_using_merge_sort (){ | |
int arraySize = 10000; | |
Record[] items = createArray(arraySize); | |
long timeBefore = System.currentTimeMillis(); | |
Arrays.sort(items); // mergesort | |
long timeAfter = System.currentTimeMillis(); | |
assertThat(timeAfter - timeBefore).isLessThan(100); | |
// 50ms on my i7 | |
} | |
@Test | |
public void it_sorts_very_fast_using_bubble_sort (){ | |
int arraySize = 10000; | |
Record[] items = createArray(arraySize); | |
long timeBefore = System.currentTimeMillis(); | |
bubbleSort(items); | |
long timeAfter = System.currentTimeMillis(); | |
assertThat(timeAfter - timeBefore).isLessThan(1100); | |
// 1000ms in my i7 | |
} | |
private void exploreItems(Record[] items) { | |
double sum = 0; | |
for (Record item : items) { | |
sum = sum + item.numericField; | |
} | |
} | |
private void bubbleSort(Record[] items) { | |
for (int i = 0; i < items.length; i++){ | |
for (int j = 0; j < items.length -1; j++){ | |
if (items[j].compareTo(items[j + 1]) > 0){ | |
Record tmp = items[j]; | |
items[j] = items[j + 1]; | |
items[j + 1] = tmp; | |
} | |
} | |
} | |
} | |
private Record[] createArray(int arraySize) { | |
Record[] items = new Record[arraySize]; | |
for (int i = 0; i < items.length; i++){ | |
items[i] = initRandomRecord(); | |
} | |
return items; | |
} | |
private Record initRandomRecord(){ | |
return new Record( | |
String.valueOf(Math.random() * 1000), Math.random() * 1000); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment