Skip to content

Commit 3f5890b

Browse files
stepanchegcarllerche
authored andcommitted
Optimize Bytes::slice(n, n) (#123)
Return empty `Bytes` object Bench for `slice_empty` difference is ``` 55 ns/iter (+/- 1) # before this patch 17 ns/iter (+/- 5) # with this patch ``` Bench for `slice_not_empty` is ``` 25,058 ns/iter (+/- 1,099) # before this patch 25,072 ns/iter (+/- 1,593) # with this patch ```
1 parent 70ee87e commit 3f5890b

File tree

3 files changed

+35
-1
lines changed

3 files changed

+35
-1
lines changed

benches/bytes.rs

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ extern crate bytes;
44
extern crate test;
55

66
use test::Bencher;
7-
use bytes::{BytesMut, BufMut};
7+
use bytes::{Bytes, BytesMut, BufMut};
88

99
#[bench]
1010
fn alloc_small(b: &mut Bencher) {
@@ -126,3 +126,23 @@ fn drain_write_drain(b: &mut Bencher) {
126126
test::black_box(parts);
127127
})
128128
}
129+
130+
#[bench]
131+
fn slice_empty(b: &mut Bencher) {
132+
b.iter(|| {
133+
// Use empty vec to avoid measure of allocation/deallocation
134+
let bytes = Bytes::from(Vec::new());
135+
(bytes.slice(0, 0), bytes)
136+
})
137+
}
138+
139+
#[bench]
140+
fn slice_not_empty(b: &mut Bencher) {
141+
b.iter(|| {
142+
let b = Bytes::from(b"aabbccddeeffgghh".to_vec());
143+
for _ in 0..1024 {
144+
test::black_box(b.slice(3, 5));
145+
test::black_box(&b);
146+
}
147+
})
148+
}

src/bytes.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -464,6 +464,11 @@ impl Bytes {
464464
/// Requires that `begin <= end` and `end <= self.len()`, otherwise slicing
465465
/// will panic.
466466
pub fn slice(&self, begin: usize, end: usize) -> Bytes {
467+
if begin == end {
468+
assert!(begin <= self.len());
469+
return Bytes::new();
470+
}
471+
467472
let mut ret = self.clone();
468473

469474
unsafe {

tests/test_bytes.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,15 @@ fn slice() {
7979
let b = a.slice(3, 5);
8080
assert_eq!(b, b"lo"[..]);
8181

82+
let b = a.slice(0, 0);
83+
assert_eq!(b, b""[..]);
84+
85+
let b = a.slice(3, 3);
86+
assert_eq!(b, b""[..]);
87+
88+
let b = a.slice(a.len(), a.len());
89+
assert_eq!(b, b""[..]);
90+
8291
let b = a.slice_to(5);
8392
assert_eq!(b, b"hello"[..]);
8493

0 commit comments

Comments
 (0)