Junior — Middle
What makes goroutines more efficient compared to traditional threads?
sobes.tech AI
Answer from AI
Goroutines in Go are more efficient compared to traditional threads due to several key features:
- Lightweight: Goroutines occupy very little memory (usually around 2 KB of stack), whereas system threads require much more memory.
- Language-level scheduler: Go has its own goroutine scheduler that efficiently distributes their execution across system threads, allowing thousands of goroutines to run simultaneously without significant overhead.
- Fast creation and context switching: Creating and switching between goroutines is much faster than between OS threads, reducing multitasking costs.
Example of creating a goroutine:
func sayHello() {
fmt.Println("Hello from goroutine")
}
func main() {
go sayHello() // start goroutine
time.Sleep(time.Second) // wait for the goroutine to finish
}