Sobes.tech
Middle+

What makes goroutines switch faster?

sobes.tech AI

Answer from AI

Goroutines switch faster because they are implemented at the user-space level, not the operating system kernel. This allows:

  • Lightweightness: a goroutine takes much less memory (usually a few kilobytes of stack) than an OS thread.
  • Fast scheduling: the goroutine scheduler is built into the Go runtime and operates without system calls, making context switches faster.
  • Multithreading with an M:N model: the Go runtime maps many goroutines onto fewer or equal OS threads, efficiently utilizing resources.

Thus, switching between goroutines does not require costly kernel context switch operations, significantly speeding up the process and increasing scalability.

Example:

func main() {
    go func() {
        fmt.Println("Goroutine 1")
    }()
    go func() {
        fmt.Println("Goroutine 2")
    }()
    time.Sleep(time.Second)
}

Here, two goroutines are launched and switch very quickly without the overhead characteristic of OS threads.