[Tcl] gets or read - which is faster

Usually, I use "gets" to read a text file.
But I tried "read" to know which is really faster.

proc test_gets {f} {
	set ch [open [format {|nkf -s "%s"} $f]]
	while {![eof $ch]} {
	    if {[gets $ch line] != -1} {
	        puts $line
	close $ch
proc test_read {f} {
	set ch [open [format {|nkf -s "%s"} $f]]
	set txt [read $ch]
	close $ch
	set lines [split $txt \n]
	foreach line $lines {
	    puts $line
set filename [file join [pwd] "hoge.txt"]
set bench1 [time {test_gets $filename} 10]
set bench2 [time {test_read $filename} 10]
puts $bench1
puts $bench2

# 1162 bytes
# gets => 39963 microseconds per iteration
# read => 27447 microseconds per iteration

# 10350085 bytes
# gets => 6420444 microseconds per iteration
# read => 6246802 microseconds per iteration

If you read the whole text, "read" is a little faster.
But if you stop reading in the middle of the content, "gets" is more efficient.

"read" uses more memory as the file size increases.

Though "read" is a little bit faster in some situation,
I think "gets" is more efficient in most cases.


このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください