I have the following Go code:
package main
import ("fmt"
"os"
"bufio")
func main() {
reader := bufio.NewReader(os.Stdin)
scanner := bufio.NewScanner(reader)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
}
and the following Python code:
import sys
for ln in sys.stdin:
print ln,
Both simply read lines from standard input and print to standard output. The Python version only uses 1/4 of the time the Go version needs (tested on a 16 million line text file and output to /dev/null). Why is that?
UPDATE: Following JimB and siritinga's advice, I changed Go's output to a buffered version. Now the Go version is much faster, but still about 75% slower than the Python version.
package main
import ("os"
"bufio")
func main() {
reader := bufio.NewReader(os.Stdin)
scanner := bufio.NewScanner(reader)
writer := bufio.NewWriter(os.Stdout)
for scanner.Scan() {
writer.WriteString(scanner.Text()+"\n")
}
}