Skip to content

Commit

Permalink
Auto merge of #52672 - ljedrz:unstable_sorts, r=<try>
Browse files Browse the repository at this point in the history
Prefer sort_unstable*() over sort*()

Since `sort_unstable` is considered typically faster than the regular `sort` ([benchmarks](#40601 (comment))), it might be a good idea to check for potential wins in the compiler.
  • Loading branch information
bors committed Jul 24, 2018
2 parents f498e4e + b520c42 commit 90ec471
Show file tree
Hide file tree
Showing 41 changed files with 68 additions and 68 deletions.
2 changes: 1 addition & 1 deletion src/librustc/hir/lowering.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4803,6 +4803,6 @@ fn body_ids(bodies: &BTreeMap<hir::BodyId, hir::Body>) -> Vec<hir::BodyId> {
// Sorting by span ensures that we get things in order within a
// file, and also puts the files in a sensible order.
let mut body_ids: Vec<_> = bodies.keys().cloned().collect();
body_ids.sort_by_key(|b| bodies[b].value.span);
body_ids.sort_unstable_by_key(|b| bodies[b].value.span);
body_ids
}
2 changes: 1 addition & 1 deletion src/librustc/hir/pat_util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ impl hir::Pat {
}
true
});
variants.sort();
variants.sort_unstable();
variants.dedup();
variants
}
Expand Down
2 changes: 1 addition & 1 deletion src/librustc/infer/error_reporting/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -434,7 +434,7 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
};

// sort the errors by span, for better error message stability.
errors.sort_by_key(|u| match *u {
errors.sort_unstable_by_key(|u| match *u {
RegionResolutionError::ConcreteFailure(ref sro, _, _) => sro.span(),
RegionResolutionError::GenericBoundFailure(ref sro, _, _) => sro.span(),
RegionResolutionError::SubSupConflict(ref rvo, _, _, _, _) => rvo.span(),
Expand Down
4 changes: 2 additions & 2 deletions src/librustc/infer/lexical_region_resolve/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -568,8 +568,8 @@ impl<'cx, 'gcx, 'tcx> LexicalResolver<'cx, 'gcx, 'tcx> {
_ => 2,
}
}
lower_bounds.sort_by_key(region_order_key);
upper_bounds.sort_by_key(region_order_key);
lower_bounds.sort_unstable_by_key(region_order_key);
upper_bounds.sort_unstable_by_key(region_order_key);

for lower_bound in &lower_bounds {
for upper_bound in &upper_bounds {
Expand Down
2 changes: 1 addition & 1 deletion src/librustc/middle/resolve_lifetime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1426,7 +1426,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
.collect();

// ensure that we issue lints in a repeatable order
def_ids.sort_by_key(|&def_id| self.tcx.def_path_hash(def_id));
def_ids.sort_unstable_by_key(|&def_id| self.tcx.def_path_hash(def_id));

for def_id in def_ids {
debug!(
Expand Down
4 changes: 2 additions & 2 deletions src/librustc/session/code_stats.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ impl CodeStats {

// Primary sort: large-to-small.
// Secondary sort: description (dictionary order)
sorted.sort_by(|info1, info2| {
sorted.sort_unstable_by(|info1, info2| {
// (reversing cmp order to get large-to-small ordering)
match info2.overall_size.cmp(&info1.overall_size) {
Ordering::Equal => info1.type_description.cmp(&info2.type_description),
Expand Down Expand Up @@ -151,7 +151,7 @@ impl CodeStats {

// We want to print fields by increasing offset.
let mut fields = fields.clone();
fields.sort_by_key(|f| f.offset);
fields.sort_unstable_by_key(|f| f.offset);

for field in fields.iter() {
let FieldInfo { ref name, offset, size, align } = *field;
Expand Down
2 changes: 1 addition & 1 deletion src/librustc/session/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2401,7 +2401,7 @@ mod dep_tracking {
impl DepTrackingHash for Vec<$t> {
fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
let mut elems: Vec<&$t> = self.iter().collect();
elems.sort();
elems.sort_unstable();
Hash::hash(&elems.len(), hasher);
for (index, elem) in elems.iter().enumerate() {
Hash::hash(&index, hasher);
Expand Down
4 changes: 2 additions & 2 deletions src/librustc/ty/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -288,15 +288,15 @@ impl<'a, 'tcx> LayoutCx<'tcx, TyCtxt<'a, 'tcx, 'tcx>> {
match kind {
StructKind::AlwaysSized |
StructKind::MaybeUnsized => {
optimizing.sort_by_key(|&x| {
optimizing.sort_unstable_by_key(|&x| {
// Place ZSTs first to avoid "interesting offsets",
// especially with only one or two non-ZST fields.
let f = &fields[x as usize];
(!f.is_zst(), cmp::Reverse(field_align(f)))
});
}
StructKind::Prefixed(..) => {
optimizing.sort_by_key(|&x| field_align(&fields[x as usize]));
optimizing.sort_unstable_by_key(|&x| field_align(&fields[x as usize]));
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/librustc/util/time_graph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ impl TimeGraph {
let mut threads: Vec<PerThread> =
table.values().map(|data| data.clone()).collect();

threads.sort_by_key(|timeline| timeline.timings[0].start);
threads.sort_unstable_by_key(|timeline| timeline.timings[0].start);

let earliest_instant = threads[0].timings[0].start;
let latest_instant = threads.iter()
Expand Down
2 changes: 1 addition & 1 deletion src/librustc_codegen_llvm/back/write.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1923,7 +1923,7 @@ fn start_executing_work(tcx: TyCtxt,
// Regardless of what order these modules completed in, report them to
// the backend in the same order every time to ensure that we're handing
// out deterministic results.
compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
compiled_modules.sort_unstable_by(|a, b| a.name.cmp(&b.name));

let compiled_metadata_module = compiled_metadata_module
.expect("Metadata module not compiled?");
Expand Down
6 changes: 3 additions & 3 deletions src/librustc_codegen_llvm/base.rs
Original file line number Diff line number Diff line change
Expand Up @@ -925,7 +925,7 @@ pub fn codegen_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
println!("n_inlines: {}", all_stats.n_inlines);
println!("n_closures: {}", all_stats.n_closures);
println!("fn stats:");
all_stats.fn_stats.sort_by_key(|&(_, insns)| insns);
all_stats.fn_stats.sort_unstable_by_key(|&(_, insns)| insns);
for &(ref name, insns) in all_stats.fn_stats.iter() {
println!("{} insns, {}", insns, *name);
}
Expand Down Expand Up @@ -1037,7 +1037,7 @@ fn collect_and_partition_mono_items<'a, 'tcx>(
output.push_str(" @@");
let mut empty = Vec::new();
let cgus = item_to_cgus.get_mut(i).unwrap_or(&mut empty);
cgus.as_mut_slice().sort_by_key(|&(ref name, _)| name.clone());
cgus.as_mut_slice().sort_unstable_by_key(|&(ref name, _)| name.clone());
cgus.dedup();
for &(ref cgu_name, (linkage, _)) in cgus.iter() {
output.push_str(" ");
Expand Down Expand Up @@ -1065,7 +1065,7 @@ fn collect_and_partition_mono_items<'a, 'tcx>(
})
.collect();

item_keys.sort();
item_keys.sort_unstable();

for item in item_keys {
println!("MONO_ITEM {}", item);
Expand Down
6 changes: 3 additions & 3 deletions src/librustc_driver/driver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1003,7 +1003,7 @@ where
.iter()
.cloned()
.collect();
missing_fragment_specifiers.sort();
missing_fragment_specifiers.sort_unstable();
for span in missing_fragment_specifiers {
let lint = lint::builtin::MISSING_FRAGMENT_SPECIFIER;
let msg = "missing fragment specifier";
Expand Down Expand Up @@ -1530,7 +1530,7 @@ pub fn collect_crate_types(session: &Session, attrs: &[ast::Attribute]) -> Vec<c
session,
));
}
base.sort();
base.sort_unstable();
base.dedup();
}

Expand Down Expand Up @@ -1562,7 +1562,7 @@ pub fn compute_crate_disambiguator(session: &Session) -> CrateDisambiguator {
let mut metadata = session.opts.cg.metadata.clone();
// We don't want the crate_disambiguator to dependent on the order
// -C metadata arguments, so sort them:
metadata.sort();
metadata.sort_unstable();
// Every distinct -C metadata value is only incorporated once:
metadata.dedup();

Expand Down
8 changes: 4 additions & 4 deletions src/librustc_driver/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1051,7 +1051,7 @@ impl RustcDefaultCalls {
match *req {
TargetList => {
let mut targets = rustc_target::spec::get_targets().collect::<Vec<String>>();
targets.sort();
targets.sort_unstable();
println!("{}", targets.join("\n"));
},
Sysroot => println!("{}", sess.sysroot().display()),
Expand Down Expand Up @@ -1117,7 +1117,7 @@ impl RustcDefaultCalls {
});
}

cfgs.sort();
cfgs.sort_unstable();
for cfg in cfgs {
println!("{}", cfg);
}
Expand Down Expand Up @@ -1229,8 +1229,8 @@ Available lint options:
fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>)
-> Vec<(&'static str, Vec<lint::LintId>)> {
let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect();
lints.sort_by(|&(x, _): &(&'static str, Vec<lint::LintId>),
&(y, _): &(&'static str, Vec<lint::LintId>)| {
lints.sort_unstable_by(|&(x, _): &(&'static str, Vec<lint::LintId>),
&(y, _): &(&'static str, Vec<lint::LintId>)| {
x.cmp(y)
});
lints
Expand Down
4 changes: 2 additions & 2 deletions src/librustc_driver/profile/trace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -208,8 +208,8 @@ pub fn write_counts(count_file: &mut File, counts: &mut HashMap<String,QueryMetr
for (ref cons, ref qm) in counts.iter() {
data.push((cons.clone(), qm.count.clone(), qm.dur_total.clone(), qm.dur_self.clone()));
};
data.sort_by(|&(_,_,_,self1),&(_,_,_,self2)|
if self1 > self2 { Ordering::Less } else { Ordering::Greater } );
data.sort_unstable_by(|&(_,_,_,self1),&(_,_,_,self2)|
if self1 > self2 { Ordering::Less } else { Ordering::Greater } );
for (cons, count, dur_total, dur_self) in data {
write!(count_file, "{}, {}, {}, {}\n",
cons, count,
Expand Down
8 changes: 4 additions & 4 deletions src/librustc_errors/emitter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ impl EmitterWriter {
line_index,
annotations: vec![ann],
});
slot.lines.sort();
slot.lines.sort_unstable();
return;
}
}
Expand Down Expand Up @@ -265,7 +265,7 @@ impl EmitterWriter {
}

// Find overlapping multiline annotations, put them at different depths
multiline_annotations.sort_by(|a, b| {
multiline_annotations.sort_unstable_by(|a, b| {
(a.1.line_start, a.1.line_end).cmp(&(b.1.line_start, b.1.line_end))
});
for item in multiline_annotations.clone() {
Expand Down Expand Up @@ -403,7 +403,7 @@ impl EmitterWriter {
// otherwise the lines would end up needing to go over a message.

let mut annotations = line.annotations.clone();
annotations.sort_by(|a,b| b.start_col.cmp(&a.start_col));
annotations.sort_unstable_by(|a,b| b.start_col.cmp(&a.start_col));

// First, figure out where each label will be positioned.
//
Expand Down Expand Up @@ -681,7 +681,7 @@ impl EmitterWriter {
// | | |
// | | something about `foo`
// | something about `fn foo()`
annotations_position.sort_by(|a, b| {
annotations_position.sort_unstable_by(|a, b| {
// Decreasing order
a.1.len().cmp(&b.1.len()).reverse()
});
Expand Down
4 changes: 2 additions & 2 deletions src/librustc_errors/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ impl CodeSuggestion {
self.substitutions.iter().cloned().map(|mut substitution| {
// Assumption: all spans are in the same file, and all spans
// are disjoint. Sort in ascending order.
substitution.parts.sort_by_key(|part| part.span.lo());
substitution.parts.sort_unstable_by_key(|part| part.span.lo());

// Find the bounding span.
let lo = substitution.parts.iter().map(|part| part.span.lo()).min().unwrap();
Expand Down Expand Up @@ -618,7 +618,7 @@ impl Handler {
})
.collect::<Vec<_>>();
if !error_codes.is_empty() {
error_codes.sort();
error_codes.sort_unstable();
if error_codes.len() > 1 {
let limit = if error_codes.len() > 9 { 9 } else { error_codes.len() };
self.failure(&format!("Some errors occurred: {}{}",
Expand Down
2 changes: 1 addition & 1 deletion src/librustc_metadata/cstore_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -356,7 +356,7 @@ pub fn provide<'tcx>(providers: &mut Providers<'tcx>) {
// we believe that libstd is consistently assigned crate
// num 1, so it should be enough to resolve #46112.
let mut crates: Vec<CrateNum> = (*tcx.crates()).clone();
crates.sort();
crates.sort_unstable();

for &cnum in crates.iter() {
// Ignore crates without a corresponding local `extern crate` item.
Expand Down
2 changes: 1 addition & 1 deletion src/librustc_metadata/encoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1438,7 +1438,7 @@ impl<'a, 'b: 'a, 'tcx: 'b> IsolatedEncoder<'a, 'b, 'tcx> {
})
.collect::<Vec<_>>();

deps.sort_by_key(|&(cnum, _)| cnum);
deps.sort_unstable_by_key(|&(cnum, _)| cnum);

{
// Sanity-check the crate numbers
Expand Down
4 changes: 2 additions & 2 deletions src/librustc_mir/borrow_check/move_errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -324,7 +324,7 @@ impl<'a, 'gcx, 'tcx> MirBorrowckCtxt<'a, 'gcx, 'tcx> {
}
}

binds_to.sort();
binds_to.sort_unstable();
binds_to.dedup();
for local in binds_to {
let bind_to = &self.mir.local_decls[local];
Expand All @@ -344,7 +344,7 @@ impl<'a, 'gcx, 'tcx> MirBorrowckCtxt<'a, 'gcx, 'tcx> {
GroupedMoveError::MovesFromPattern { mut binds_to, .. } => {
// Suggest ref, since there might be a move in
// another match arm
binds_to.sort();
binds_to.sort_unstable();
binds_to.dedup();
for local in binds_to {
let bind_to = &self.mir.local_decls[local];
Expand Down
2 changes: 1 addition & 1 deletion src/librustc_mir/borrow_check/nll/region_infer/dump_mir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ impl<'tcx> RegionInferenceContext<'tcx> {
}

let mut constraints: Vec<_> = self.constraints.iter().collect();
constraints.sort();
constraints.sort_unstable();
for constraint in &constraints {
let OutlivesConstraint {
sup,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ impl<'tcx> RegionInferenceContext<'tcx> {
debug!("report_error: categorized_path={:?}", categorized_path);

// Find what appears to be the most interesting path to report to the user.
categorized_path.sort_by(|p0, p1| p0.0.cmp(&p1.0));
categorized_path.sort_unstable_by(|p0, p1| p0.0.cmp(&p1.0));
debug!("report_error: sorted_path={:?}", categorized_path);

// Get a span
Expand Down
2 changes: 1 addition & 1 deletion src/librustc_mir/borrow_check/nll/region_infer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -418,7 +418,7 @@ impl<'tcx> RegionInferenceContext<'tcx> {

debug!("propagate_constraints: constraints={:#?}", {
let mut constraints: Vec<_> = self.constraints.iter().collect();
constraints.sort();
constraints.sort_unstable();
constraints
});

Expand Down
4 changes: 2 additions & 2 deletions src/librustc_mir/build/matches/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
let source_info = self.source_info(span);

let mut otherwise = otherwise;
otherwise.sort();
otherwise.sort_unstable();
otherwise.dedup(); // variant switches can introduce duplicate target blocks
for block in otherwise {
self.cfg.terminate(block, source_info, TerminatorKind::Unreachable);
Expand Down Expand Up @@ -644,7 +644,7 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
-> BasicBlock
{
let source_info = self.source_info(span);
otherwise.sort();
otherwise.sort_unstable();
otherwise.dedup(); // variant switches can introduce duplicate target blocks
if otherwise.len() == 1 {
otherwise[0]
Expand Down
2 changes: 1 addition & 1 deletion src/librustc_mir/interpret/memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,7 @@ impl<'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'a, 'mir, 'tcx, M> {
return;
}
use std::fmt::Write;
allocs.sort();
allocs.sort_unstable();
allocs.dedup();
let mut allocs_to_print = VecDeque::from(allocs);
let mut allocs_seen = FxHashSet::default();
Expand Down
2 changes: 1 addition & 1 deletion src/librustc_mir/monomorphize/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ pub fn assert_symbols_are_distinct<'a, 'tcx, I>(tcx: TyCtxt<'a, 'tcx, 'tcx>, mon
(mono_item, mono_item.symbol_name(tcx))
}).collect();

(&mut symbols[..]).sort_by(|&(_, ref sym1), &(_, ref sym2)|{
(&mut symbols[..]).sort_unstable_by(|&(_, ref sym1), &(_, ref sym2)|{
sym1.cmp(sym2)
});

Expand Down
4 changes: 2 additions & 2 deletions src/librustc_mir/monomorphize/partitioning.rs
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,7 @@ pub fn partition<'a, 'tcx, I>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
internalization_candidates: _,
} = post_inlining;

result.sort_by(|cgu1, cgu2| {
result.sort_unstable_by(|cgu1, cgu2| {
cgu1.name().cmp(cgu2.name())
});

Expand Down Expand Up @@ -502,7 +502,7 @@ fn merge_codegen_units<'tcx>(initial_partitioning: &mut PreInliningPartitioning<
// smallest into each other) we're sure to start off with a deterministic
// order (sorted by name). This'll mean that if two cgus have the same size
// the stable sort below will keep everything nice and deterministic.
codegen_units.sort_by_key(|cgu| cgu.name().clone());
codegen_units.sort_unstable_by_key(|cgu| cgu.name().clone());

// Merge the two smallest codegen units until the target size is reached.
while codegen_units.len() > target_cgu_count {
Expand Down
2 changes: 1 addition & 1 deletion src/librustc_mir/transform/check_unsafety.rs
Original file line number Diff line number Diff line change
Expand Up @@ -501,7 +501,7 @@ pub fn check_unsafety<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) {
}

let mut unsafe_blocks: Vec<_> = unsafe_blocks.into_iter().collect();
unsafe_blocks.sort();
unsafe_blocks.sort_unstable();
let used_unsafe: FxHashSet<_> = unsafe_blocks.iter()
.flat_map(|&&(id, used)| if used { Some(id) } else { None })
.collect();
Expand Down
2 changes: 1 addition & 1 deletion src/librustc_mir/util/patch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ impl<'tcx> MirPatch<'tcx> {
}

let mut new_statements = self.new_statements;
new_statements.sort_by(|u,v| u.0.cmp(&v.0));
new_statements.sort_unstable_by(|u,v| u.0.cmp(&v.0));

let mut delta = 0;
let mut last_bb = START_BLOCK;
Expand Down
Loading

0 comments on commit 90ec471

Please sign in to comment.