在Ruby中,File可以用readlines跟跑while迴圈來讀
在這個例子中,程式p1用的是while迴圈,p2用的是readlines
執行後,秒數分別是
P1:
121.468秒
P2:
122.172秒
範例文字檔大小是:
4.07 MB (4,272,336 位元組)

範例程式碼是:

puts "P1 start"
p1_start = Time.now
open("C:/words.txt"){ |f|
  while a = f.gets
    print a
  end
}
p1_end = Time.now
puts "P1 end"
puts "P2 start"
p2_start = Time.now
File.open("C:/words.txt") do |f|
  puts f.readlines
end
p2_end = Time.now
puts "P2 end"
puts
puts "P1: ", p1_end - p1_start
puts "P2: ", p2_end - p2_start

由此可見,while快上不到一秒,但是如果在讀取大檔案的時候,用while反而會比較快
相對的,如果不考慮效率,我還是建議使用readlines

不過這只是個人看法,希望其他前輩不吝指教,謝謝!
arrow
arrow
    全站熱搜

    hechian 發表在 痞客邦 留言(0) 人氣()