Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Taproot sig message #3

Merged
merged 3 commits into from
Aug 31, 2021

Conversation

Kixunil
Copy link

@Kixunil Kixunil commented Aug 10, 2021

These changes replace unwrap() with get_or_insert_with() in cache methods. The commits explain why performance shouldn't be lost.

There was a question whether this is equally performant. There are
multiple good reasons why it should be:

1. `get_or_insert_with` is marked `#[inline]`
2. Any good optimizer will inline a function that is used exactly once
3. 1 and 2 conclude that the closure will get inlined
4. Computing self.tx can then be moved to the only branch where it is
   required.
5. Even if get_or_insert_with didn't get optimized, which is extremely
   unlikely, the `tx` field is at the beginning of the struct and it
   probably has pointer alignment (`Deref` suggests it's a pointer).
   Alignment larger than pointer is not used, so we can expect the
   fields to be ordered as-defined. (This is not guaranteed by Rust but
   there's not good reason to change the order in this case.) We can
   assume that offset to tx is zero in most cases which means no
   computation is actually needed so the expression before closure is
   no-op short of passing it into the closure as an argument.

At the time of writing `#[inline]` can be seen at
https://doc.rust-lang.org/src/core/option.rs.html#933
This refactors the code to make it possible to use `get_or_insert_with`
instead of unwrapping in `segwit_cache()`. To achieve it `common_cache`
is refactored into two functions: one taking only the required borrows
and the original calling the new one. `segwit_cache` then calls the new
function so that borrows are OK.

Apart from removing unwrap, this avoids calling `common_cache` multiple
times.
@Kixunil
Copy link
Author

Kixunil commented Aug 10, 2021

Thinking about it a bit more, if cache miss is very rare we could make the closures #[cold] possibly saving bunch of instructions in the cache. Seems better than saving one addition. But I wouldn't date to mess with it without actually measuring.

@RCasatta
Copy link
Owner

I am in PTO at the moment but I did a quick look and I think I am going to merge this.

Just I am not doing it now because I need some time to dedicate to this and other comments in the PR...

@RCasatta RCasatta merged commit 0777491 into RCasatta:taproot_sig_message Aug 31, 2021
@Kixunil Kixunil deleted the taproot_sig_message branch August 31, 2021 12:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
2 participants