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

perf: optimize u8_slice_to_hex by replacing Vec with String #270

Merged
merged 2 commits into from
Nov 18, 2024

Conversation

CosminPerRam
Copy link
Contributor

It builds a String, which is a Vec at its core, so we can replace it (also avoid to build it afterwards).

A quick benchmark on a 25-length array (about the same difference with the doc/test example one):

test tests::original         ... bench:         107.91 ns/iter (+/- 5.20)
test tests::string_container ... bench:          85.96 ns/iter (+/- 7.89)

(Ryzen 5 3600, Windows 11)

Benchmark code

Run via cargo +nightly bench.

#![feature(test)]

extern crate test;

const HEX_TABLE: [u8; 16] = [
  b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7', b'8', b'9', b'a', b'b', b'c', b'd', b'e', b'f',
];

fn u8_slice_to_hex(slice: &[u8]) -> String {
  let mut hex = Vec::with_capacity(slice.len() * 2 + 2);
  hex.push(b'0');
  hex.push(b'x');
  for b in slice.iter() {
      hex.push(HEX_TABLE[(b >> 4) as usize]);
      hex.push(HEX_TABLE[(b & 0x0F) as usize]);
  }

  String::from_utf8(hex).unwrap()
}

const HEX_TABLE2: [char; 16] = [
  '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
];

fn u8_slice_to_hex2(slice: &[u8]) -> String {
  let mut hex = String::with_capacity(slice.len() * 2 + 2);
  hex.push_str("0x");
  for b in slice {
      hex.push(HEX_TABLE2[(b >> 4) as usize]);
      hex.push(HEX_TABLE2[(b & 0x0F) as usize]);
  }
  hex
}

const SOME_NUMS: [u8; 25] = [
  12, 98, 54, 213, 47,
  162, 89, 73, 250, 34,
  150, 19, 245, 8, 60,
  111, 203, 77, 135, 42,
  176, 29, 91, 68, 231,
];

#[cfg(test)]
mod tests {
  use super::*;
  use test::Bencher;

  #[bench]
  fn original(b: &mut Bencher) {
      b.iter(|| u8_slice_to_hex(&SOME_NUMS));
  }

  #[bench]
  fn string_container(b: &mut Bencher) {
      b.iter(|| u8_slice_to_hex2(&SOME_NUMS));
  }
}

Copy link
Owner

@keepsimple1 keepsimple1 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for your PR! Nice optimization, LGTM!

@keepsimple1 keepsimple1 merged commit b50fe8c into keepsimple1:main Nov 18, 2024
3 checks passed
@CosminPerRam CosminPerRam deleted the perf/u8_slice_to_hex branch November 18, 2024 11:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants