Skip to content

How to simplify tokio::join! when calls too much ? #4442

Answered by Darksonn
loongs-zhang asked this question in Q&A
Discussion options

You must be logged in to vote

When you are spawning a very large number of tasks, then you should be spawning them as separate tasks rather than using things like tokio::join! as this will lead to better performance. The code below shows how you can do that:

let mut handles = Vec::new();
for i in 0..1000 {
    handles.push(tokio::spawn(request(i.to_string())));
}

let mut output = Vec::with_capacity(handles.len());
for handle in handles {
    output.push(handle.await.unwrap());
}

Be aware that the above code will run them in parallel even though they are not immediately .awaited. This is due to the tokio::spawn call, which will start any task passed to it immediately.

We are currently working on new features to make t…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@loongs-zhang
Comment options

Answer selected by loongs-zhang
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants