Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

slightly related: earlier I was experimenting with Rust string allocations, even though my code did almost same as standard library, the heap allocations were taking 10x of time. Relevant code:

  fn alloc_string(s: &str) -> NonNull<u8> {
      let boxed_slice = s.as_bytes().to_owned().into_boxed_slice();
      NonNull::new(Box::into_raw(boxed_slice) as *mut u8).unwrap()
  }

Approximately, if stdlib was taking 1µs, but my code was about 14-15µs for large strings. Profiling also did not help. Anyone have any guesses? Here is the full code: https://github.com/avinassh/string-alloc


When you call to_owned, it creates a Vec<u8>. This must then be truncated due to the call to into_boxed_slice. The documentation says this could potentially mean a re-allocation depending on the allocator. When this happens the old allocation needs to be dropped too. You could try using a different allocator but before this I would recommend to replace those two calls with Box::from(s.as_bytes()).


The vec already gets allocated with capacity == length

https://doc.rust-lang.org/nightly/src/alloc/slice.rs.html#16...




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: