Skip to content

Instantly share code, notes, and snippets.

@morris821028
Created July 16, 2018 12:23
Show Gist options
  • Save morris821028/7f8973b5927084bc24060e3cbdef302a to your computer and use it in GitHub Desktop.
Save morris821028/7f8973b5927084bc24060e3cbdef302a to your computer and use it in GitHub Desktop.
Java Iterator Performance - HashSet/TreeSet
import java.util.*;
public class Main {
static class Point implements Comparable<Point> {
long x;
long y;
public Point(long x, long y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Point o) {
if (x != o.x)
return Long.compare(x, o.x);
return Long.compare(y, o.y);
}
public boolean equals(Object o) {
if (o instanceof Point)
return this.compareTo((Point) o) == 0;
return false;
}
@Override
public int hashCode() {
return (int) (x ^ y);
}
}
static long iterator(Set<Point> A, Set<Point> B) {
long startTime = System.currentTimeMillis();
long sum = 0;
for (int it = 0; it < 10; it++) {
for (Point p : A) {
for (Point q : B)
sum += p.x * q.y;
}
}
long estimatedTime = System.currentTimeMillis() - startTime;
System.out.printf("%d %X\n", estimatedTime, sum);
return estimatedTime;
}
public static void main(String[] args) {
HashSet<Point> A, B;
TreeSet<Point> C, D;
Random rand = new Random();
A = new HashSet<>();
B = new HashSet<>();
C = new TreeSet<>();
D = new TreeSet<>();
for (int i = 0; i < 500000; i++) {
long x = rand.nextLong();
long y = rand.nextLong();
Point p = new Point(x, y);
A.add(p);
C.add(p);
}
for (int i = 0; i < 1; i++) {
long x = rand.nextLong();
long y = rand.nextLong();
Point p = new Point(x, y);
B.add(p);
D.add(p);
}
for (int i = 0; i < 10; i++) {
System.out.println("HashSet");
iterator(A, B);
System.out.println("TreeSet");
iterator(C, D);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment