java - Array / Vector as method argument -


i have read should use vector everywhere in java , there no performance issues, true. i'm writing method calculate mse (mean squared error) , noticed slow - passing vector of values. when switched array, 10 times faster don't understand why.

i have written simple test:

public static void main(string[] args) throws ioexception {      vector <integer> testv = new vector<integer>();     integer[] testa = new integer[1000000];     for(int i=0;i<1000000;i++){         testv.add(i);         testa[i]=i;     }      long starttime = system.currenttimemillis();     for(int i=0;i<500;i++){         double testval = testarray(testa, 0, 1000000);     }     system.out.println(string.format("array total time %s ",system.currenttimemillis() - starttime));      starttime = system.currenttimemillis();     for(int i=0;i<500;i++){         double testval = testvector(testv, 0, 1000000);     }     system.out.println(string.format("vector total time %s ",system.currenttimemillis() - starttime));  } 

which calls following methods:

public static double testvector(vector<integer> data, int start, int stop){     double toto = 0.0;     for(int i=start ; i<stop ; i++){         toto += data.get(i);     }      return toto / data.size(); }  public static double testarray(integer[] data, int start, int stop){     double toto = 0.0;     for(int i=start ; i<stop ; i++){         toto += data[i];     }      return toto / data.length; } 

the array 1 indeed 10 times faster. here output:

array total time 854 vector total time 9840

can explain me why ? have searched quite while, cannot figure out. vector method appears making local copy of vector, thought objects passed reference in java.

i have read should use vector everywhere in java , there no performance issues, - wrong. vector thread safe , needs additional logic (code) handle access/ modification multiple threads so, slow. array on other hand doesn't need additional logic handle multiple threads. should try arraylist instead of vector increase speed

note (based on comment): i'm running method 500 times each

this not right way measure performance / speed in java. should atleast give warm-up run nullify effect of jit.


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -