Skip to content

Commit 726fde7

Browse files
committed
Optimise async callbacks (polling)
call async Rust callback [sum] 3 10 time: [59.338 us 59.729 us 60.097 us] change: [-10.336% -8.6212% -6.8003%] (p = 0.00 < 0.05) Performance has improved.
1 parent 7cb9c4f commit 726fde7

File tree

2 files changed

+15
-6
lines changed

2 files changed

+15
-6
lines changed

benches/benchmark.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ extern "system" {}
1313
use criterion::{criterion_group, criterion_main, BatchSize, Criterion};
1414
use std::time::Duration;
1515
use tokio::runtime::Runtime;
16+
use tokio::task;
1617

1718
use mlua::prelude::*;
1819

@@ -117,7 +118,10 @@ fn call_sum_callback(c: &mut Criterion) {
117118
fn call_async_sum_callback(c: &mut Criterion) {
118119
let lua = Lua::new();
119120
let callback = lua
120-
.create_async_function(|_, (a, b, c): (i64, i64, i64)| async move { Ok(a + b + c) })
121+
.create_async_function(|_, (a, b, c): (i64, i64, i64)| async move {
122+
task::yield_now().await;
123+
Ok(a + b + c)
124+
})
121125
.unwrap();
122126
lua.globals().set("callback", callback).unwrap();
123127

src/lua.rs

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1735,10 +1735,9 @@ impl Lua {
17351735

17361736
match (*fut).as_mut().poll(&mut ctx) {
17371737
Poll::Pending => {
1738-
check_stack(state, 6)?;
1738+
check_stack(state, 1)?;
17391739
ffi::lua_pushboolean(state, 0);
1740-
push_gc_userdata(state, AsyncPollPending)?;
1741-
Ok(2)
1740+
Ok(1)
17421741
}
17431742
Poll::Ready(results) => {
17441743
let results = results?;
@@ -1782,18 +1781,24 @@ impl Lua {
17821781
))
17831782
})?,
17841783
)?;
1784+
env.set("pending", unsafe {
1785+
let _sg = StackGuard::new(self.state);
1786+
check_stack(self.state, 5)?;
1787+
push_gc_userdata(self.state, AsyncPollPending)?;
1788+
self.pop_value()
1789+
})?;
17851790

17861791
// We set `poll` variable in the env table to be able to destroy upvalues
17871792
self.load(
17881793
r#"
17891794
poll = get_poll(...)
1790-
local poll, yield, unpack = poll, yield, unpack
1795+
local poll, pending, yield, unpack = poll, pending, yield, unpack
17911796
while true do
17921797
local ready, res, nres = poll()
17931798
if ready then
17941799
return unpack(res, nres)
17951800
end
1796-
yield(res)
1801+
yield(pending)
17971802
end
17981803
"#,
17991804
)

0 commit comments

Comments
 (0)