Skip to content

Commit f11502c

Browse files
committed
Auto merge of #26904 - bluss:no-repeat, r=alexcrichton
In a followup to PR #26849, improve one more location for I/O where we can use `Vec::resize` to ensure better performance when zeroing buffers. Use the `vec![elt; n]` macro everywhere we can in the tree. It replaces `repeat(elt).take(n).collect()` which is more verbose, requires type hints, and right now produces worse code. `vec![]` is preferable for vector initialization. The `vec![]` replacement touches upon one I/O path too, Stdin::read for windows, and that should be a small improvement. r? @alexcrichton
2 parents 517e087 + 836f32e commit f11502c

File tree

32 files changed

+64
-93
lines changed

32 files changed

+64
-93
lines changed

src/libcollections/bit.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -283,7 +283,7 @@ impl BitVec {
283283
pub fn from_elem(nbits: usize, bit: bool) -> BitVec {
284284
let nblocks = blocks_for_bits(nbits);
285285
let mut bit_vec = BitVec {
286-
storage: repeat(if bit { !0 } else { 0 }).take(nblocks).collect(),
286+
storage: vec![if bit { !0 } else { 0 }; nblocks],
287287
nbits: nbits
288288
};
289289
bit_vec.fix_last_block();

src/libcollectionstest/slice.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -1318,7 +1318,7 @@ mod bench {
13181318

13191319
#[bench]
13201320
fn mut_iterator(b: &mut Bencher) {
1321-
let mut v: Vec<_> = repeat(0).take(100).collect();
1321+
let mut v = vec![0; 100];
13221322

13231323
b.iter(|| {
13241324
let mut i = 0;
@@ -1419,7 +1419,7 @@ mod bench {
14191419
#[bench]
14201420
fn zero_1kb_from_elem(b: &mut Bencher) {
14211421
b.iter(|| {
1422-
repeat(0u8).take(1024).collect::<Vec<_>>()
1422+
vec![0u8; 1024]
14231423
});
14241424
}
14251425

@@ -1467,7 +1467,7 @@ mod bench {
14671467
fn random_inserts(b: &mut Bencher) {
14681468
let mut rng = thread_rng();
14691469
b.iter(|| {
1470-
let mut v: Vec<_> = repeat((0, 0)).take(30).collect();
1470+
let mut v = vec![(0, 0); 30];
14711471
for _ in 0..100 {
14721472
let l = v.len();
14731473
v.insert(rng.gen::<usize>() % (l + 1),
@@ -1479,7 +1479,7 @@ mod bench {
14791479
fn random_removes(b: &mut Bencher) {
14801480
let mut rng = thread_rng();
14811481
b.iter(|| {
1482-
let mut v: Vec<_> = repeat((0, 0)).take(130).collect();
1482+
let mut v = vec![(0, 0); 130];
14831483
for _ in 0..100 {
14841484
let l = v.len();
14851485
v.remove(rng.gen::<usize>() % l);

src/libcoretest/ptr.rs

+2-3
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010

1111
use core::ptr::*;
1212
use core::mem;
13-
use std::iter::repeat;
1413

1514
#[test]
1615
fn test() {
@@ -110,7 +109,7 @@ fn test_as_mut() {
110109
#[test]
111110
fn test_ptr_addition() {
112111
unsafe {
113-
let xs = repeat(5).take(16).collect::<Vec<_>>();
112+
let xs = vec![5; 16];
114113
let mut ptr = xs.as_ptr();
115114
let end = ptr.offset(16);
116115

@@ -128,7 +127,7 @@ fn test_ptr_addition() {
128127
m_ptr = m_ptr.offset(1);
129128
}
130129

131-
assert!(xs_mut == repeat(10).take(16).collect::<Vec<_>>());
130+
assert!(xs_mut == vec![10; 16]);
132131
}
133132
}
134133

src/libgraphviz/lib.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -599,7 +599,6 @@ mod tests {
599599
use std::io;
600600
use std::io::prelude::*;
601601
use std::borrow::IntoCow;
602-
use std::iter::repeat;
603602

604603
/// each node is an index in a vector in the graph.
605604
type Node = usize;
@@ -647,7 +646,7 @@ mod tests {
647646
fn to_opt_strs(self) -> Vec<Option<&'static str>> {
648647
match self {
649648
UnlabelledNodes(len)
650-
=> repeat(None).take(len).collect(),
649+
=> vec![None; len],
651650
AllNodesLabelled(lbls)
652651
=> lbls.into_iter().map(
653652
|l|Some(l)).collect(),

src/librand/reseeding.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,7 @@ mod tests {
186186
const FILL_BYTES_V_LEN: usize = 13579;
187187
#[test]
188188
fn test_rng_fill_bytes() {
189-
let mut v = repeat(0).take(FILL_BYTES_V_LEN).collect::<Vec<_>>();
189+
let mut v = vec![0; FILL_BYTES_V_LEN];
190190
::test::rng().fill_bytes(&mut v);
191191

192192
// Sanity test: if we've gotten here, `fill_bytes` has not infinitely

src/librustc/middle/check_match.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -704,7 +704,7 @@ fn is_useful(cx: &MatchCheckCtxt,
704704
match is_useful(cx, &matrix, v.tail(), witness) {
705705
UsefulWithWitness(pats) => {
706706
let arity = constructor_arity(cx, &constructor, left_ty);
707-
let wild_pats: Vec<_> = repeat(DUMMY_WILD_PAT).take(arity).collect();
707+
let wild_pats = vec![DUMMY_WILD_PAT; arity];
708708
let enum_pat = construct_witness(cx, &constructor, wild_pats, left_ty);
709709
let mut new_pats = vec![enum_pat];
710710
new_pats.extend(pats);
@@ -862,7 +862,7 @@ pub fn specialize<'a>(cx: &MatchCheckCtxt, r: &[&'a Pat],
862862
} = raw_pat(r[col]);
863863
let head: Option<Vec<&Pat>> = match *node {
864864
ast::PatWild(_) =>
865-
Some(repeat(DUMMY_WILD_PAT).take(arity).collect()),
865+
Some(vec![DUMMY_WILD_PAT; arity]),
866866

867867
ast::PatIdent(_, _, _) => {
868868
let opt_def = cx.tcx.def_map.borrow().get(&pat_id).map(|d| d.full_def());
@@ -875,7 +875,7 @@ pub fn specialize<'a>(cx: &MatchCheckCtxt, r: &[&'a Pat],
875875
} else {
876876
None
877877
},
878-
_ => Some(repeat(DUMMY_WILD_PAT).take(arity).collect())
878+
_ => Some(vec![DUMMY_WILD_PAT; arity])
879879
}
880880
}
881881

@@ -889,7 +889,7 @@ pub fn specialize<'a>(cx: &MatchCheckCtxt, r: &[&'a Pat],
889889
DefVariant(..) | DefStruct(..) => {
890890
Some(match args {
891891
&Some(ref args) => args.iter().map(|p| &**p).collect(),
892-
&None => repeat(DUMMY_WILD_PAT).take(arity).collect(),
892+
&None => vec![DUMMY_WILD_PAT; arity],
893893
})
894894
}
895895
_ => None

src/librustc/middle/dataflow.rs

+6-7
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@ use middle::cfg::CFGIndex;
2121
use middle::ty;
2222
use std::io;
2323
use std::usize;
24-
use std::iter::repeat;
2524
use syntax::ast;
2625
use syntax::ast_util::IdRange;
2726
use syntax::visit;
@@ -239,11 +238,11 @@ impl<'a, 'tcx, O:DataFlowOperator> DataFlowContext<'a, 'tcx, O> {
239238

240239
let entry = if oper.initial_value() { usize::MAX } else {0};
241240

242-
let zeroes: Vec<_> = repeat(0).take(num_nodes * words_per_id).collect();
243-
let gens: Vec<_> = zeroes.clone();
244-
let kills1: Vec<_> = zeroes.clone();
245-
let kills2: Vec<_> = zeroes;
246-
let on_entry: Vec<_> = repeat(entry).take(num_nodes * words_per_id).collect();
241+
let zeroes = vec![0; num_nodes * words_per_id];
242+
let gens = zeroes.clone();
243+
let kills1 = zeroes.clone();
244+
let kills2 = zeroes;
245+
let on_entry = vec![entry; num_nodes * words_per_id];
247246

248247
let nodeid_to_index = build_nodeid_to_index(decl, cfg);
249248

@@ -511,7 +510,7 @@ impl<'a, 'tcx, O:DataFlowOperator+Clone+'static> DataFlowContext<'a, 'tcx, O> {
511510
changed: true
512511
};
513512

514-
let mut temp: Vec<_> = repeat(0).take(words_per_id).collect();
513+
let mut temp = vec![0; words_per_id];
515514
while propcx.changed {
516515
propcx.changed = false;
517516
propcx.reset(&mut temp);

src/librustc/middle/infer/region_inference/mod.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,6 @@ use util::nodemap::{FnvHashMap, FnvHashSet};
3434
use std::cell::{Cell, RefCell};
3535
use std::cmp::Ordering::{self, Less, Greater, Equal};
3636
use std::fmt;
37-
use std::iter::repeat;
3837
use std::u32;
3938
use syntax::ast;
4039

@@ -1304,7 +1303,7 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> {
13041303
// idea is to report errors that derive from independent
13051304
// regions of the graph, but not those that derive from
13061305
// overlapping locations.
1307-
let mut dup_vec: Vec<_> = repeat(u32::MAX).take(self.num_vars() as usize).collect();
1306+
let mut dup_vec = vec![u32::MAX; self.num_vars() as usize];
13081307

13091308
for idx in 0..self.num_vars() as usize {
13101309
match var_data[idx].value {

src/librustc/middle/liveness.rs

+2-3
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,6 @@ use util::nodemap::NodeMap;
119119
use std::{fmt, usize};
120120
use std::io::prelude::*;
121121
use std::io;
122-
use std::iter::repeat;
123122
use std::rc::Rc;
124123
use syntax::ast::{self, NodeId, Expr};
125124
use syntax::codemap::{BytePos, original_sp, Span};
@@ -566,8 +565,8 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> {
566565
Liveness {
567566
ir: ir,
568567
s: specials,
569-
successors: repeat(invalid_node()).take(num_live_nodes).collect(),
570-
users: repeat(invalid_users()).take(num_live_nodes * num_vars).collect(),
568+
successors: vec![invalid_node(); num_live_nodes],
569+
users: vec![invalid_users(); num_live_nodes * num_vars],
571570
loop_scope: Vec::new(),
572571
break_ln: NodeMap(),
573572
cont_ln: NodeMap(),

src/librustc_back/sha2.rs

+2-4
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212
//! use. This implementation is not intended for external use or for any use where security is
1313
//! important.
1414
15-
use std::iter::repeat;
1615
use std::slice::bytes::{MutableByteVector, copy_memory};
1716
use serialize::hex::ToHex;
1817

@@ -255,7 +254,7 @@ pub trait Digest {
255254
/// Convenience function that retrieves the result of a digest as a
256255
/// newly allocated vec of bytes.
257256
fn result_bytes(&mut self) -> Vec<u8> {
258-
let mut buf: Vec<u8> = repeat(0).take((self.output_bits()+7)/8).collect();
257+
let mut buf = vec![0; (self.output_bits()+7)/8];
259258
self.result(&mut buf);
260259
buf
261260
}
@@ -534,7 +533,6 @@ mod tests {
534533
use self::rand::Rng;
535534
use self::rand::isaac::IsaacRng;
536535
use serialize::hex::FromHex;
537-
use std::iter::repeat;
538536
use std::u64;
539537
use super::{Digest, Sha256, FixedBuffer};
540538

@@ -613,7 +611,7 @@ mod tests {
613611
/// correct.
614612
fn test_digest_1million_random<D: Digest>(digest: &mut D, blocksize: usize, expected: &str) {
615613
let total_size = 1000000;
616-
let buffer: Vec<u8> = repeat('a' as u8).take(blocksize * 2).collect();
614+
let buffer = vec![b'a'; blocksize * 2];
617615
let mut rng = IsaacRng::new_unseeded();
618616
let mut count = 0;
619617

src/librustc_data_structures/bitvec.rs

+1-3
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,6 @@
88
// option. This file may not be copied, modified, or distributed
99
// except according to those terms.
1010

11-
use std::iter;
12-
1311
/// A very simple BitVector type.
1412
pub struct BitVector {
1513
data: Vec<u64>
@@ -18,7 +16,7 @@ pub struct BitVector {
1816
impl BitVector {
1917
pub fn new(num_bits: usize) -> BitVector {
2018
let num_words = (num_bits + 63) / 64;
21-
BitVector { data: iter::repeat(0).take(num_words).collect() }
19+
BitVector { data: vec![0; num_words] }
2220
}
2321

2422
fn word_mask(&self, bit: usize) -> (usize, u64) {

src/librustc_trans/trans/cabi_x86_64.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@ use trans::context::CrateContext;
2121
use trans::type_::Type;
2222

2323
use std::cmp;
24-
use std::iter::repeat;
2524

2625
#[derive(Clone, Copy, PartialEq)]
2726
enum RegClass {
@@ -319,7 +318,7 @@ fn classify_ty(ty: Type) -> Vec<RegClass> {
319318
}
320319

321320
let words = (ty_size(ty) + 7) / 8;
322-
let mut cls: Vec<_> = repeat(NoClass).take(words).collect();
321+
let mut cls = vec![NoClass; words];
323322
if words > 4 {
324323
all_mem(&mut cls);
325324
return cls;

src/librustc_trans/trans/consts.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,6 @@ use middle::subst::Substs;
3535
use middle::ty::{self, Ty};
3636
use util::nodemap::NodeMap;
3737

38-
use std::iter::repeat;
3938
use libc::c_uint;
4039
use syntax::{ast, ast_util};
4140
use syntax::parse::token;
@@ -780,7 +779,7 @@ fn const_expr_unadjusted<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
780779
let llunitty = type_of::type_of(cx, unit_ty);
781780
let n = cx.tcx().eval_repeat_count(count);
782781
let unit_val = const_expr(cx, &**elem, param_substs, fn_args).0;
783-
let vs: Vec<_> = repeat(unit_val).take(n).collect();
782+
let vs = vec![unit_val; n];
784783
if val_ty(unit_val) != llunitty {
785784
C_struct(cx, &vs[..], false)
786785
} else {

src/librustc_trans/trans/expr.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,6 @@ use syntax::{ast, ast_util, codemap};
8383
use syntax::parse::token::InternedString;
8484
use syntax::ptr::P;
8585
use syntax::parse::token;
86-
use std::iter::repeat;
8786
use std::mem;
8887

8988
// Destinations
@@ -1400,7 +1399,7 @@ fn trans_struct<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
14001399

14011400
let tcx = bcx.tcx();
14021401
with_field_tys(tcx, ty, Some(expr_id), |discr, field_tys| {
1403-
let mut need_base: Vec<bool> = repeat(true).take(field_tys.len()).collect();
1402+
let mut need_base = vec![true; field_tys.len()];
14041403

14051404
let numbered_fields = fields.iter().map(|field| {
14061405
let opt_pos =

src/librustc_trans/trans/type_.rs

+2-3
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@ use std::ffi::CString;
2323
use std::mem;
2424
use std::ptr;
2525
use std::cell::RefCell;
26-
use std::iter::repeat;
2726

2827
use libc::c_uint;
2928

@@ -253,7 +252,7 @@ impl Type {
253252
if n_elts == 0 {
254253
return Vec::new();
255254
}
256-
let mut elts: Vec<_> = repeat(Type { rf: ptr::null_mut() }).take(n_elts).collect();
255+
let mut elts = vec![Type { rf: ptr::null_mut() }; n_elts];
257256
llvm::LLVMGetStructElementTypes(self.to_ref(),
258257
elts.as_mut_ptr() as *mut TypeRef);
259258
elts
@@ -267,7 +266,7 @@ impl Type {
267266
pub fn func_params(&self) -> Vec<Type> {
268267
unsafe {
269268
let n_args = llvm::LLVMCountParamTypes(self.to_ref()) as usize;
270-
let mut args: Vec<_> = repeat(Type { rf: ptr::null_mut() }).take(n_args).collect();
269+
let mut args = vec![Type { rf: ptr::null_mut() }; n_args];
271270
llvm::LLVMGetParamTypes(self.to_ref(),
272271
args.as_mut_ptr() as *mut TypeRef);
273272
args

src/librustc_typeck/astconv.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,6 @@ use rscope::{self, UnelidableRscope, RegionScope, ElidableRscope, ExplicitRscope
6464
use util::common::{ErrorReported, FN_OUTPUT_NAME};
6565
use util::nodemap::FnvHashSet;
6666

67-
use std::iter::repeat;
6867
use std::slice;
6968
use syntax::{abi, ast, ast_util};
7069
use syntax::codemap::{Span, Pos};
@@ -588,7 +587,7 @@ fn convert_parenthesized_parameters<'tcx>(this: &AstConv<'tcx>,
588587
0, &region_substs, a_t))
589588
.collect::<Vec<Ty<'tcx>>>();
590589

591-
let input_params: Vec<_> = repeat(String::new()).take(inputs.len()).collect();
590+
let input_params = vec![String::new(); inputs.len()];
592591
let implied_output_region = find_implied_output_region(this.tcx(), &inputs, input_params);
593592

594593
let input_ty = this.tcx().mk_tup(inputs);

src/librustc_typeck/check/method/confirm.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ use middle::infer;
2020
use middle::infer::InferCtxt;
2121
use syntax::ast;
2222
use syntax::codemap::Span;
23-
use std::iter::repeat;
2423

2524
struct ConfirmContext<'a, 'tcx:'a> {
2625
fcx: &'a FnCtxt<'a, 'tcx>,
@@ -322,7 +321,7 @@ impl<'a,'tcx> ConfirmContext<'a,'tcx> {
322321
} else if num_supplied_types != num_method_types {
323322
span_err!(self.tcx().sess, self.span, E0036,
324323
"incorrect number of type parameters given for this method");
325-
repeat(self.tcx().types.err).take(num_method_types).collect()
324+
vec![self.tcx().types.err; num_method_types]
326325
} else {
327326
supplied_method_types
328327
}

0 commit comments

Comments
 (0)