Can very simple for loop be slower in go than in Ruby?

Hello, I’ve started learning Ruby and Go simultaneously and I completed one of the simplest challenges there using both languages. The goal of the challenge is to print every odd number between 0 and 100. My go code was:

package main
import "fmt"
func main() {
	for i := 1; i < 100; i = i + 2 {
		fmt.Println(i)
	}
}

In ruby I used:

i = 0
while i < 100
 puts i
 i = i + 2
end

The result was correct for both, but time of execution surprised me. Ruby executed code in 133ms, but Go made it in 744. Can someone please explain me, what is wrong with my code, or why the Go was so much slower? Thank you for any advice.

How are you testing? If you’re not using a proper benchmarking framework you’re probably testing the startup time of the binary and so on and not the actual loop. Even if you are benchmarking properly, are you comparing like to like? For example, Go doesn’t use output buffering by default - does Ruby?

Figure out what aspect takes time in the respective case and you might have your answer.

Or even better, don’t worry about benchmarking things that don’t matter, and benchmark that which does matter. :wink:

Go is a compiled language, of you’re doing something like time go run test.go then you’re benchmarking the time it takes to compile the program as well as run it.

The other difference is that in go fmt.Println is not buffered, whereas it is in Ruby. So you may be benchmarking how quickly your terminal scrolls.

1 Like

Ok, I really dont even know what does buffering mean (ok, I’ve read something about it just right now, because of your comments). That time i posted is from the website itself. I am really not concerned. I am on the veery beggining of programming. I was just curious, as I read how Go should be faster because. But I don’t know anything about how the measuring work, if it cound compilation etc. So thank you very much. You pointed out some reasons and I am quite satisfied now :slight_smile: Sorry for bad english and thanks for answering quite banal question.

I wouldn’t worry about random results on a website. If you are concerned about performance, benchmark your own code.

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.