Skip to content

Instantly share code, notes, and snippets.

@promatik
Last active November 28, 2017 17:46
Show Gist options
  • Save promatik/6f8da9ac1371dcd18e830925e7c6aa78 to your computer and use it in GitHub Desktop.
Save promatik/6f8da9ac1371dcd18e830925e7c6aa78 to your computer and use it in GitHub Desktop.
HashMap vs Object variable cast performance test
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
new Main();
}
public ArrayList<Socket> list = new ArrayList<>();
public HashMap<Integer, User> map = new HashMap<>();
public Main() {
for (int i = 0; i < 10000000; i++) {
User user = new User(i);
Socket socket = new Socket(i);
socket.setVariables(user);
list.add(socket);
map.put(i, user);
}
while(true)
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
int value = Integer.parseInt(br.readLine());
Socket socket = list.get(value);
// From MAP
long start = System.nanoTime();
map.get(socket.getId());
System.out.println(System.nanoTime() - start);
// From VARIABLES
start = System.nanoTime();
socket.getVariables();
System.out.println(System.nanoTime() - start);
} catch (Exception e) {
System.err.println("Value out of range.");
}
}
}
}
123
31362 // From Map
1824 // From cast
1
4741
364
1
4011
364
1
3282
365
9999
19692
365
public class Socket {
private Object variables;
private int id;
public Socket(int id) {
this.id = id;
}
public int getId() {
return id;
}
@SuppressWarnings("unchecked")
public <T> T getVariables() { return (T) variables; }
@SuppressWarnings("unchecked")
public <T> T getVariables(Class<T> type) { return (T) variables; }
public <T> void setVariables(T variables) { this.variables = variables; }
}
public class User {
private long id = 0L;
public User(long id) {
this.id = id;
}
public long getId() {
return id;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment