Are ArrayLists more than twice as slow as arrays?

后端 未结 4 749
傲寒
傲寒 2021-01-02 02:06

I wrote a test that attempts to test two things:

  • Whether the size of a buffer array affects its performance, even if you don\'t use the whole buffer
  • T
4条回答
  •  鱼传尺愫
    2021-01-02 02:09

    If you store millions of objects, then the Add or Contains functions will be super slow. Best way is to split it using hashMap of Arrays. Although similar algorithms can be used for other types of objects, this is how I improved 1000 times faster the processing of 10 million strings (the memory taken is 2-3 times more)

    public static class ArrayHashList  {
        private String temp1, temp2;
        HashMap allKeys = new HashMap();
        ArrayList curKeys;  
        private int keySize;
        public ArrayHashList(int keySize) {
            this.keySize = keySize;
        }   
        public ArrayHashList(int keySize, String fromFileName) {
            this.keySize = keySize;
            String line;
            try{
                BufferedReader br1 = new BufferedReader(new FileReader(fromFileName));        
                while ((line = br1.readLine()) != null) 
                    addString(line);
                br1.close();
            }catch(Exception e){
                e.printStackTrace();
            }
        }   
        public boolean addString(String strToAdd) {  
            if (strToAdd.length()

    to init and use it:

    ArrayHashList fullHlist = new ArrayHashList(3, filesPath+"\\allPhrases.txt");       
    ArrayList pendingList = new ArrayList();
    BufferedReader br1 = new BufferedReader(new FileReader(filesPath + "\\processedPhrases.txt"));
    while ((line = br1.readLine()) != null) {
        wordEnc = StrUtil.GetFirstToken(line,",~~~,");
        if (!fullHlist.haveString(wordEnc))
            pendingList.add(wordEnc);
    }
    br1.close();    
    

提交回复
热议问题