Skip to content

Commit 1eafb40

Browse files
authored
Improve fold bench data generation (#9210)
1 parent 9f4fa5b commit 1eafb40

File tree

1 file changed

+30
-15
lines changed

1 file changed

+30
-15
lines changed

src/uu/fold/benches/fold_bench.rs

Lines changed: 30 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,20 +4,19 @@
44
// file that was distributed with this source code.
55

66
use divan::{Bencher, black_box};
7-
use std::fmt::Write;
87
use uu_fold::uumain;
98
use uucore::benchmark::{create_test_file, run_util_function};
109

1110
/// Benchmark folding many short lines
1211
#[divan::bench(args = [100_000])]
1312
fn fold_many_lines(bencher: Bencher, num_lines: usize) {
1413
let temp_dir = tempfile::tempdir().unwrap();
15-
// Create long lines that need folding
16-
let data = (0..num_lines)
17-
.fold(String::new(), |mut acc, i| {
18-
writeln!(&mut acc, "This is a very long line number {i} that definitely needs to be folded at the default width of 80 columns").unwrap();
19-
acc
20-
});
14+
let mut data = String::with_capacity(num_lines * 110);
15+
for i in 0..num_lines {
16+
data.push_str("This is a very long line number ");
17+
append_usize(&mut data, i);
18+
data.push_str(" that definitely needs to be folded at the default width of 80 columns\n");
19+
}
2120
let file_path = create_test_file(data.as_bytes(), temp_dir.path());
2221
let file_path_str = file_path.to_str().unwrap();
2322

@@ -30,14 +29,12 @@ fn fold_many_lines(bencher: Bencher, num_lines: usize) {
3029
#[divan::bench(args = [50_000])]
3130
fn fold_custom_width(bencher: Bencher, num_lines: usize) {
3231
let temp_dir = tempfile::tempdir().unwrap();
33-
let data = (0..num_lines).fold(String::new(), |mut acc, i| {
34-
writeln!(
35-
&mut acc,
36-
"Line {i} with enough text to exceed width 40 characters and require folding"
37-
)
38-
.unwrap();
39-
acc
40-
});
32+
let mut data = String::with_capacity(num_lines * 80);
33+
for i in 0..num_lines {
34+
data.push_str("Line ");
35+
append_usize(&mut data, i);
36+
data.push_str(" with enough text to exceed width 40 characters and require folding\n");
37+
}
4138
let file_path = create_test_file(data.as_bytes(), temp_dir.path());
4239
let file_path_str = file_path.to_str().unwrap();
4340

@@ -49,3 +46,21 @@ fn fold_custom_width(bencher: Bencher, num_lines: usize) {
4946
fn main() {
5047
divan::main();
5148
}
49+
50+
fn append_usize(buf: &mut String, mut value: usize) {
51+
let mut digits = [0u8; 20];
52+
let mut idx = digits.len();
53+
54+
if value == 0 {
55+
buf.push('0');
56+
return;
57+
}
58+
59+
while value > 0 {
60+
idx -= 1;
61+
digits[idx] = b'0' + (value % 10) as u8;
62+
value /= 10;
63+
}
64+
65+
buf.push_str(std::str::from_utf8(&digits[idx..]).unwrap());
66+
}

0 commit comments

Comments
 (0)