Skip to content

Instantly share code, notes, and snippets.

@maxd

maxd/Main.java Secret

Last active Aug 29, 2015
Embed
What would you like to do?
Instantiation of TreeItem's (JavaFX)
import javafx.scene.control.TreeItem;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
int count = 1_000_000;
Object[] o = new Object[count];
try(StopWatch stopWatch = StopWatch.startNew("Instantiate Objects")) {
for (int i = 0; i < count; i++) {
o[i] = new Object();
}
}
ArrayList[] a = (ArrayList[]) Array.newInstance(ArrayList.class, count);
try(StopWatch stopWatch = StopWatch.startNew("Instantiate ArrayLists")) {
for (int i = 0; i < count; i++) {
a[i] = new ArrayList();
}
}
HashMap[] hm = (HashMap[]) Array.newInstance(HashMap.class, count);
try(StopWatch stopWatch = StopWatch.startNew("Instantiate HashMaps")) {
for (int i = 0; i < count; i++) {
hm[i] = new HashMap();
}
}
TreeItem[] ti = (TreeItem[]) Array.newInstance(TreeItem.class, count);
try(StopWatch stopWatch = StopWatch.startNew("Instantiate TreeItems")) {
for (int i = 0; i < count; i++) {
ti[i] = new TreeItem();
}
}
}
}
Instantiate Objects: 0.12657099962234497 sec.
Instantiate ArrayLists: 0.19151298701763153 sec.
Instantiate HashMaps: 0.21388199925422668 sec.
Instantiate TreeItems: 11.619612693786621 sec.
import java.io.Closeable;
@SuppressWarnings("unused")
public class StopWatch implements Closeable {
private String title;
private long elapsedTime;
private long startTime;
private boolean started;
private StopWatch(String title) {
this.title = title;
}
public static StopWatch startNew(String title) {
final StopWatch stopWatch = new StopWatch(title);
stopWatch.start();
return stopWatch;
}
public void start() {
if (started) {
return;
}
startTime = System.nanoTime();
started = true;
}
public void reset() {
elapsedTime = 0;
startTime = System.nanoTime();
}
public void stop() {
if (!started) {
return;
}
started = false;
elapsedTime += (System.nanoTime() - startTime);
}
public long getElapsedTime() {
if (started) {
return elapsedTime + (System.nanoTime() - startTime);
}
return elapsedTime;
}
public double getElapsedMilliseconds() {
return getElapsedTime() / 1000000.0f;
}
public double getElapsedSeconds() {
return getElapsedTime() / 1000000000.0f;
}
public String toString() {
return title + ": " + getElapsedSeconds() + " sec.";
}
public long getStartTime() {
return startTime;
}
public double getStartMilliseconds() {
return getStartTime() / 1000000.0f;
}
public boolean isStarted() {
return started;
}
public void close() {
stop();
System.out.println(this);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment