Questioning the design of the "Future" trait, and the cost implied by it

This is well-known: the advantage of the Rust design is that it's much more memory and cache efficient in the common shallow cases, since you only need one memory allocation for the whole future/task chain without any pointers to the next tasks and the data is contiguous in memory reducing cache misses. The CPU time for going a few levels deep is negligible compared to the CPU time needed to send I/O to the kernel.

Of course you need to avoid any sort of unbounded recursion: fortunately, it's easy to avoid doing it accidentally since it will not compile unless you explicitly box the futures, which is an indicator that you are probably doing something wrong.

If you really need it, then spawning on an executor is the correct approach as you stated. It's not an "hack" and should not incur more overhead than in JavaScript.

If you want to fully emulate the JavaScript design in Rust you in addition to spawning tasks use the Shared adapter, which will give something that behaves exactly like a JavaScript promise (which obviously is a bad idea in general since it's inefficient).

3 Likes