java - Performance of ArrayList vs HashSet -


i know prefer arraylist on hashset when need store duplicates, , hashset uses hashcode() function calculate index each element in array.

so, means if want store single element, arraylist should take less time hashset. please correct me if wrong anywhere.

but when checking performance through code getting different behavior.

case 1:

import java.util.*; class hashsetvsarraylist {  public static void main(string args[])  {   arraylist<integer> a1=new arraylist<integer>();   long nanos = system.nanotime();    a1.add(1);    system.out.println("arraylist time:"+(system.nanotime()-nanos)+"ns");    hashset<integer> h1=new hashset<integer>();   nanos = system.nanotime();    h1.add(2);    system.out.println("hashset insertion time:"+(system.nanotime()-nanos)+"ns");  } } 
output: arraylist time:495087ns hashset insertion time:21757ns 

case 2:

import java.util.*; class hashsetvsarraylist {  public static void main(string args[])  {   hashset<integer> h1=new hashset<integer>();   long nanos = system.nanotime();    h1.add(2);    system.out.println("hashset insertion time:"+(system.nanotime()-nanos)+"ns");    arraylist<integer> a1=new arraylist<integer>();   nanos = system.nanotime();    a1.add(1);    system.out.println("arraylist time:"+(system.nanotime()-nanos)+"ns");  } } 
output: hashset insertion time:582527ns arraylist time:21758ns 

now, assume hashset should take more time insertion of single element. but, in both cases behavior different...less time taken data structure comes second in code. also, behavior changes when number of elements inserted more 1000.

please explain happening.

your benchmark broken. read: dynamic compilation , performance measurement and: anatomy of flawed microbenchmark before trying benchmark in java.

the short explanation total time duration trying measure there much, much short, , benchmark results swamped tiny os , cpu details, , fact java vm still busy compiling bytecode machine code while begins run.

meanwhile, bit mad compare arraylist , hashlist on performance when serve 2 different purposes, else being equal, implementation of arraylist significantly simpler, assumption surely correct; faster.


Popular posts from this blog