Skip to content

Commit 6483ef5

Browse files
authored
Merge pull request #890 from rust-ndarray/jt-scalar-ops-improvement
Scalar + &array and &array + scalar performance improvements
2 parents 3f10677 + dcf38e8 commit 6483ef5

File tree

2 files changed

+20
-4
lines changed

2 files changed

+20
-4
lines changed

benches/bench1.rs

+16
Original file line numberDiff line numberDiff line change
@@ -433,6 +433,22 @@ fn scalar_add_2(bench: &mut test::Bencher) {
433433
bench.iter(|| n + &a);
434434
}
435435

436+
#[bench]
437+
fn scalar_add_strided_1(bench: &mut test::Bencher) {
438+
let a =
439+
Array::from_shape_fn((64, 64 * 2), |(i, j)| (i * 64 + j) as f32).slice_move(s![.., ..;2]);
440+
let n = 1.;
441+
bench.iter(|| &a + n);
442+
}
443+
444+
#[bench]
445+
fn scalar_add_strided_2(bench: &mut test::Bencher) {
446+
let a =
447+
Array::from_shape_fn((64, 64 * 2), |(i, j)| (i * 64 + j) as f32).slice_move(s![.., ..;2]);
448+
let n = 1.;
449+
bench.iter(|| n + &a);
450+
}
451+
436452
#[bench]
437453
fn scalar_sub_1(bench: &mut test::Bencher) {
438454
let a = Array::<f32, _>::zeros((64, 64));

src/impl_ops.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -159,8 +159,8 @@ impl<'a, A, S, D, B> $trt<B> for &'a ArrayBase<S, D>
159159
B: ScalarOperand,
160160
{
161161
type Output = Array<A, D>;
162-
fn $mth(self, x: B) -> Array<A, D> {
163-
self.to_owned().$mth(x)
162+
fn $mth(self, x: B) -> Self::Output {
163+
self.map(move |elt| elt.clone() $operator x.clone())
164164
}
165165
}
166166
);
@@ -210,11 +210,11 @@ impl<'a, S, D> $trt<&'a ArrayBase<S, D>> for $scalar
210210
D: Dimension,
211211
{
212212
type Output = Array<$scalar, D>;
213-
fn $mth(self, rhs: &ArrayBase<S, D>) -> Array<$scalar, D> {
213+
fn $mth(self, rhs: &ArrayBase<S, D>) -> Self::Output {
214214
if_commutative!($commutative {
215215
rhs.$mth(self)
216216
} or {
217-
self.$mth(rhs.to_owned())
217+
rhs.map(move |elt| self.clone() $operator elt.clone())
218218
})
219219
}
220220
}

0 commit comments

Comments
 (0)