Speedup idx function
This commit is contained in:
parent
7979a4fbe0
commit
f28b3a3281
2 changed files with 19 additions and 19 deletions
|
@ -83,7 +83,7 @@ fn criterion_benchmark(c: &mut Criterion) {
|
|||
b.iter_batched(
|
||||
|| (rand(), rand()),
|
||||
|(x, y)| {
|
||||
let _v = vec_vec[criterion::black_box(x)][criterion::black_box(y)];
|
||||
let _v = vec_vec[x][y];
|
||||
},
|
||||
criterion::BatchSize::SmallInput,
|
||||
)
|
||||
|
@ -92,7 +92,7 @@ fn criterion_benchmark(c: &mut Criterion) {
|
|||
let grid = init_grid();
|
||||
b.iter_batched(
|
||||
|| (rand(), rand()),
|
||||
|(x, y)| grid[criterion::black_box(x)][criterion::black_box(y)],
|
||||
|(x, y)| grid[x][y],
|
||||
criterion::BatchSize::SmallInput,
|
||||
)
|
||||
});
|
||||
|
@ -102,9 +102,9 @@ fn criterion_benchmark(c: &mut Criterion) {
|
|||
|| (rand(), rand()),
|
||||
|(x, y)| {
|
||||
let _v = vec_vec
|
||||
.get(criterion::black_box(x))
|
||||
.get(x)
|
||||
.unwrap()
|
||||
.get(criterion::black_box(y))
|
||||
.get(y)
|
||||
.unwrap();
|
||||
},
|
||||
criterion::BatchSize::SmallInput,
|
||||
|
@ -116,7 +116,7 @@ fn criterion_benchmark(c: &mut Criterion) {
|
|||
|| (rand(), rand()),
|
||||
|(x, y)| {
|
||||
let _v = grid
|
||||
.get(criterion::black_box(x), criterion::black_box(y))
|
||||
.get(x, y)
|
||||
.unwrap();
|
||||
},
|
||||
criterion::BatchSize::SmallInput,
|
||||
|
|
24
src/lib.rs
24
src/lib.rs
|
@ -723,22 +723,19 @@ impl<T: Clone> Clone for Grid<T> {
|
|||
impl<T> Index<usize> for Grid<T> {
|
||||
type Output = [T];
|
||||
|
||||
fn index(&self, idx: usize) -> &Self::Output {
|
||||
if idx < self.rows {
|
||||
#[inline]
|
||||
fn index(&self, idx: usize) -> &[T] {
|
||||
let start_idx = idx * self.cols;
|
||||
&self.data[start_idx..start_idx + self.cols]
|
||||
} else {
|
||||
panic!(
|
||||
"index {:?} out of bounds. Grid has {:?} rows.",
|
||||
self.rows, idx
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> IndexMut<usize> for Grid<T> {
|
||||
fn index_mut(&mut self, idx: usize) -> &mut Self::Output {
|
||||
&mut self.data[(idx * self.cols)..]
|
||||
|
||||
#[inline]
|
||||
fn index_mut(&mut self, idx: usize) -> &mut [T] {
|
||||
let start_idx = idx * self.cols;
|
||||
&mut self.data[start_idx..start_idx + self.cols]
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -1217,8 +1214,11 @@ mod test {
|
|||
|
||||
#[test]
|
||||
fn idx() {
|
||||
let grid = Grid::init(1, 2, 3);
|
||||
assert_eq!(grid[0][0], 3);
|
||||
let grid: Grid<u8> = Grid::from_vec(vec![1, 2, 3, 4], 2);
|
||||
assert_eq!(grid[0][0], 1);
|
||||
assert_eq!(grid[0][1], 2);
|
||||
assert_eq!(grid[1][0], 3);
|
||||
assert_eq!(grid[1][1], 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
Loading…
Reference in a new issue