rss· 投稿· 设为首页· 加入收藏· 繁體版
当前位置: 火魔网 » 程序开发 » Java基础

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

http://dev.firnow.com/course/3_program/java/javajs/200889/135291.html

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


  • public static void main(String[] args) {
  •   ArrayList al = new ArrayList();
  •   try {   
  •    FileWriter fw = new FileWriter(new File("e:\\s.txt"));
  •    for(int i=0;i<1000;i++){
  •     String str = "000\t111\t222\t222\t222\t222\t222\t222\t222\t222\n";
  •     al.add(str);
  •     fw.write(str);
  •    }
  •    fw.close();
  •    FileOutputStream fileStream = new FileOutputStream("e:\\s.obj"); 
  •    ObjectOutputStream out = new ObjectOutputStream(fileStream); 
  •    out.writeObject(al);
  •    out.close(); 
  •   } catch (Exception e) {
  •    e.printStackTrace();
  •   }   
  •  }

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

    序列化读取:


  • public static void main(String[] args) {
  •   ArrayList al = new ArrayList();
  •   try {
  •    long t = System.currentTimeMillis();
  •    FileInputStream fileStream = new FileInputStream("e:\\s.obj");   
  •    BufferedInputStream br = new BufferedInputStream(fileStream); 
  •    ObjectInputStream in = new ObjectInputStream(br);
  •    al = (ArrayList)in.readObject();   
  •    in.close(); 
  •    System.out.println(System.currentTimeMillis()-t);
  •   } catch (Exception e) {
  •    e.printStackTrace();
  •   } 
  •  }

  • //文本文件读取:
  •  public static void main(String[] args) {
  •   ArrayList al = new ArrayList();
  •   try {
  •    long t = System.currentTimeMillis();
  •    FileReader fw = new FileReader(new File("e:\\s.txt"));
  •    BufferedReader br = new BufferedReader(fw);
  •    String s = br.readLine();
  •    while (s != null) {
  •     al.add(s);
  •     s = br.readLine();
  •    }
  •    br.close();
  •    fw.close();
  •    System.out.println(System.currentTimeMillis()-t);
  •   } catch (Exception e) {
  •    e.printStackTrace();
  •   }

  •  }


  • 结论:

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

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