I read about how TreeSet is slower than HashSet, (that adding elements into a TreeSet is slower) so i made a performance test, i\'m trying to find out if it\'s better to add
Try to run this code. I took it from codeforces.ru. This is the demonstration of how HashSet/HashMap may work. It took 1.3 - 1.4 sec to add 10^5 values. According to linked topic - shuffling won't help (I didn't tried). TreeSet will never show such terrible perfomance.
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class Main implements Runnable {
public static void main(String[] args) {
new Thread(null, new Main(), "", 16 * (1L << 20)).start();
}
public void run() {
try {
long t1 = System.currentTimeMillis();
solve();
long t2 = System.currentTimeMillis();
System.out.println("Time = " + (t2 - t1));
} catch (Throwable t) {
t.printStackTrace(System.err);
System.exit(-1);
}
}
// solution
int hashinv(int h) {
h ^= (h >>> 4) ^ (h >>> 7) ^ (h >>> 8) ^ (h >>> 14) ^ (h >>> 15)
^ (h >>> 18) ^ (h >>> 19) ^ (h >>> 20) ^ (h >>> 21)
^ (h >>> 23) ^ (h >>> 26) ^ (h >>> 28);
return h;
}
int bitreverse(int h) {
int res = 0;
for (int i = 0; i < 31; i++)
if ((h & (1 << i)) != 0)
res |= (1 << (30 - i));
return res;
}
void solve() throws IOException {
final int size = 100000;
int[] s = new int[size];
for (int i = 0, val = 0; i < size; i++) {
s[i] = Integer.MAX_VALUE;
while (s[i] > 1000000000)
s[i] = hashinv(bitreverse(val++));
}
long startTime = System.currentTimeMillis();
HashSet h = new HashSet(size);
for (int i = 0; i < size; i++)
h.add(s[i]);
System.out.println("HashSet adding time = " + (System.currentTimeMillis() - startTime));
}
}