Skip to content

Instantly share code, notes, and snippets.

@nagisa
Last active October 4, 2015 15:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nagisa/1ab6cb74cd470a2f5a09 to your computer and use it in GitHub Desktop.
Save nagisa/1ab6cb74cd470a2f5a09 to your computer and use it in GitHub Desktop.
#![feature(placement_in_syntax, test)]
#![feature(placement_new_protocol)]
use std::ops::{Placer, Place, InPlace};
#[cfg(test)] extern crate test;
#[cfg(test)] use test::Bencher;
pub struct MyVec<T>(Vec<T>);
pub struct MyVecEmplace<'a, T: 'a>(*mut T, &'a mut MyVec<T>);
impl<'a, T> Placer<T> for &'a mut MyVec<T> {
type Place = MyVecEmplace<'a, T>;
#[inline]
fn make_place(self) -> MyVecEmplace<'a, T> {
let length = self.0.len();
MyVecEmplace(unsafe {self.0.as_mut_ptr().offset(length as isize)}, self)
}
}
impl<'a, T> Place<T> for MyVecEmplace<'a, T> {
#[inline(always)]
fn pointer(&mut self) -> *mut T {
self.0
}
}
impl<'a, T> InPlace<T> for MyVecEmplace<'a, T> {
type Owner = ();
#[inline(always)]
unsafe fn finalize(self) -> () {
let len = (self.1).0.len();
(self.1).0.set_len(len + 1);
}
}
#[bench]
pub fn emplace(b: &mut Bencher) {
b.iter(||{
let mut x = MyVec(Vec::with_capacity(1026));
for i in 0..1024 {
in &mut x {test::black_box(i)};
}
});
}
#[bench]
pub fn push(b: &mut Bencher) {
b.iter(||{
let mut x = MyVec(Vec::with_capacity(1026));
for i in 0..1024 {
x.0.push(test::black_box(i));
}
});
}
@nagisa
Copy link
Author

nagisa commented Oct 4, 2015

running 2 tests
test emplace ... bench: 335 ns/iter (+/- 6)
test push ... bench: 1,023 ns/iter (+/- 26)

test result: ok. 0 passed; 0 failed; 0 ignored; 2 measured

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment