g10guang
g10guang

Reputation: 5305

What's difference between select{} and for{} in golang?

I find a similar question: What does an empty select do?

for{} will cover 100% cpu usage.

select{} ask the channel case can read or write or not. But no case in the select. select{} will use 0% cpu usage? Or just like the for{}?

Upvotes: 8

Views: 4951

Answers (1)

Adrian
Adrian

Reputation: 46552

for{} uses 100% CPU because it continuously executes the loop iteration.

select{} uses nearly 0% CPU because it causes the goroutine to block, which means the scheduler puts it to sleep, and it will never be woken.

Upvotes: 24

Related Questions