import org.bson.types.*; import java.util.*; public class Test { public static void main(final String [] pArgs) throws Exception { ObjectId [] objIds = new ObjectId[1000000]; String [] strs = new String[objIds.length]; for (int idx=0; idx < objIds.length; idx++) { objIds[idx] = ObjectId.get(); objIds[idx].hashCode(); strs[idx] = "123456"+idx; strs[idx].hashCode(); } for (int idx=0; idx < strs.length; idx++) { final ObjectId objId = objIds[idx]; final String str = strs[idx]; } Set set = new HashSet<>(objIds.length); // Initial for (int idx=0; idx < objIds.length; idx++) set.add("test"); set.clear(); System.gc(); Thread.sleep(2000); long startTime, execTime; // String startTime = System.currentTimeMillis(); for (int idx=0; idx < strs.length; idx++) set.add(strs[idx]); execTime = System.currentTimeMillis() - startTime; System.out.println("string: " + execTime); set.clear(); System.gc(); // ObjectId startTime = System.currentTimeMillis(); for (int idx=0; idx < objIds.length; idx++) set.add(objIds[idx]); execTime = System.currentTimeMillis() - startTime; System.out.println("objectid: " + execTime); set.clear(); System.gc(); // String startTime = System.currentTimeMillis(); for (int idx=0; idx < strs.length; idx++) set.add(strs[idx]); execTime = System.currentTimeMillis() - startTime; System.out.println("string: " + execTime); set.clear(); System.gc(); // ObjectId startTime = System.currentTimeMillis(); for (int idx=0; idx < objIds.length; idx++) set.add(objIds[idx]); execTime = System.currentTimeMillis() - startTime; System.out.println("objectid: " + execTime); } }