ink icon indicating copy to clipboard operation
ink copied to clipboard

Avoid heap allocations while debug printing

Open Robbepop opened this issue 4 years ago • 0 comments

We currently perform a heap allocation every time we use ink_env::debug_print or ink_env::debug_println macros. This is due to the usage of format! macro that constructs an instance of String: https://paritytech.github.io/ink/src/ink_env/lib.rs.html#141

We can avoid this unnecessary heap allocation and therefore make it far less expensive to use debug printing in ink! and sometimes even get rid of the expensive heap allocator altogether in less complex smart contracts.

We can do this by leveraging the same "trick" that Rust's core library does as well. Instead of using the format! macro directly we instead use the format_args! macro. Also we need to provide an API that is similar to Rust's core::fmt::write_fmt function instead of our current https://paritytech.github.io/ink/ink_env/fn.debug_message.html that takes a &str parameter. ink!'s new ink_env::debug_fmt API would instead take a core::fmt::Arguments type as single input just like Rust's core::fmt::write function but with the difference that the output: &mut dyn Write parameter does not need to be given since we simply make use of ink!'s 16kB static buffer. So as long as whatever the user prints a string that fits in this 16kB static buffer we are fine and otherwise we can panic.

The only downside is that if any core::fmt::Debug or core::fmt::Display implementation of anything the user wants to print internally makes use of ink_env APIs that also use the static 16kB buffer we run into a panic immediately. This would not be unsafe and is rather unlikely to happen. Any suggestions on this point or alternatives?

After we successfully implemented the new API we can remove ink_env::debug_message or deprecate it at least and we can relink ink_env::debug_print and ink_env::debug_println macros to use this new heap allocation avoiding API instead.

Robbepop avatar Sep 16 '21 15:09 Robbepop