java序列化读取与文本文件读取数据效率对比

来源:互联网 发布:java swing 时间控件 编辑:程序博客网 时间:2024/05/16 13:56
 

分别写入数据到序列化文件和文本文件中:

 

  1. public static void main(String[] args) {
  2.   ArrayList al = new ArrayList();
  3.   try {   
  4.    FileWriter fw = new FileWriter(new File("e://s.txt"));
  5.    for(int i=0;i<1000;i++){
  6.     String str = "000/t111/t222/t222/t222/t222/t222/t222/t222/t222/n";
  7.     al.add(str);
  8.     fw.write(str);
  9.    }
  10.    fw.close();
  11.    FileOutputStream fileStream = new FileOutputStream("e://s.obj"); 
  12.    ObjectOutputStream out = new ObjectOutputStream(fileStream); 
  13.    out.writeObject(al);
  14.    out.close(); 
  15.   } catch (Exception e) {
  16.    e.printStackTrace();
  17.   }   
  18.  }

  然后写程序读取序列化文件和文本文件,并将数据赋值到ArrayList中。

序列化读取:

 

  1. public static void main(String[] args) {
  2.   ArrayList al = new ArrayList();
  3.   try {
  4.    long t = System.currentTimeMillis();
  5.    FileInputStream fileStream = new FileInputStream("e://s.obj");   
  6.    BufferedInputStream br = new BufferedInputStream(fileStream); 
  7.    ObjectInputStream in = new ObjectInputStream(br);
  8.    al = (ArrayList)in.readObject();   
  9.    in.close(); 
  10.    System.out.println(System.currentTimeMillis()-t);
  11.   } catch (Exception e) {
  12.    e.printStackTrace();
  13.   } 
  14.  }
  15. //文本文件读取:
  16.  public static void main(String[] args) {
  17.   ArrayList al = new ArrayList();
  18.   try {
  19.    long t = System.currentTimeMillis();
  20.    FileReader fw = new FileReader(new File("e://s.txt"));
  21.    BufferedReader br = new BufferedReader(fw);
  22.    String s = br.readLine();
  23.    while (s != null) {
  24.     al.add(s);
  25.     s = br.readLine();
  26.    }
  27.    br.close();
  28.    fw.close();
  29.    System.out.println(System.currentTimeMillis()-t);
  30.   } catch (Exception e) {
  31.    e.printStackTrace();
  32.   }
  33.  }

结论:

在行数i=1000时,序列化读取平均32,文本文件读取平均16。
在行数i=10000时,序列化读取平均46,文本文件读取平均46。
在行数i=100000时,序列化读取平均96,文本文件读取平均316。

故在大数据量读取时,使用序列化方式存取数据,效率较高;而在小数据量(小于10000行)时,使用文本文件存取数据效率较高。

原创粉丝点击