Skip to content

Commit

Permalink
perf(ast-tools): use FxHashMap over std::collections::HashMap (#5997
Browse files Browse the repository at this point in the history
)
  • Loading branch information
camchenry committed Sep 23, 2024
1 parent f02bf51 commit 02d5637
Show file tree
Hide file tree
Showing 16 changed files with 53 additions and 39 deletions.
5 changes: 5 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions crates/oxc_language_server/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#[allow(clippy::disallowed_types)]
mod linter;

use std::{collections::HashMap, fmt::Debug, path::PathBuf, str::FromStr};
Expand Down
1 change: 1 addition & 0 deletions tasks/ast_tools/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ prettyplease = { workspace = true }
proc-macro2 = { workspace = true }
quote = { workspace = true }
regex = { workspace = true }
rustc-hash = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
syn = { workspace = true, features = ["clone-impls", "derive", "extra-traits", "full", "parsing", "printing", "proc-macro"] }
7 changes: 4 additions & 3 deletions tasks/ast_tools/src/codegen.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use std::{cell::RefCell, collections::HashMap, path::PathBuf};
use std::{cell::RefCell, path::PathBuf};

use itertools::Itertools;
use proc_macro2::TokenStream;
use rustc_hash::{FxBuildHasher, FxHashMap};

use crate::{
derives::{Derive, DeriveOutput},
Expand Down Expand Up @@ -69,7 +70,7 @@ pub trait Runner {

pub struct EarlyCtx {
ty_table: Vec<AstRef>,
ident_table: HashMap<String, TypeId>,
ident_table: FxHashMap<String, TypeId>,
mods: RefCell<Vec<rust_ast::Module>>,
}

Expand All @@ -80,7 +81,7 @@ impl EarlyCtx {
let adts = mods.iter().flat_map(|it| it.items.iter());

let mut ty_table = Vec::with_capacity(len);
let mut ident_table = HashMap::with_capacity(len);
let mut ident_table = FxHashMap::with_capacity_and_hasher(len, FxBuildHasher);
for adt in adts {
if let Some(ident) = adt.borrow().ident() {
let ident = ident.to_string();
Expand Down
5 changes: 3 additions & 2 deletions tasks/ast_tools/src/derives/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,10 +77,11 @@ macro_rules! define_derive {
}

fn run(&mut self, ctx: &$crate::codegen::LateCtx) -> $crate::Result<Self::Output> {
use std::collections::{HashMap, HashSet};
use std::collections::{HashSet};
use std::vec::Vec;
use convert_case::{Case, Casing};
use itertools::Itertools;
use rustc_hash::FxHashMap;

use $crate::derives::DeriveTemplate;

Expand All @@ -90,7 +91,7 @@ macro_rules! define_derive {
.into_iter()
.filter(|def| def.generates_derive(trait_name))
.map(|def| (def, self.derive(def, ctx)))
.fold(HashMap::<&str, (HashSet<&str>, Vec<TokenStream>)>::new(), |mut acc, (def, stream)| {
.fold(FxHashMap::<&str, (HashSet<&str>, Vec<TokenStream>)>::default(), |mut acc, (def, stream)| {
let module_path = def.module_path();
let krate = module_path.split("::").next().unwrap();
if !acc.contains_key(krate) {
Expand Down
5 changes: 3 additions & 2 deletions tasks/ast_tools/src/generators/ast_builder.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
use std::{borrow::Cow, collections::HashMap, stringify};
use std::{borrow::Cow, stringify};

use convert_case::{Case, Casing};
use itertools::Itertools;
use lazy_static::lazy_static;
use proc_macro2::TokenStream;
use quote::{format_ident, quote, ToTokens};
use rustc_hash::FxHashMap;
use syn::{parse_quote, Ident, Type};

use super::define_generator;
Expand Down Expand Up @@ -226,7 +227,7 @@ fn default_init_field(field: &FieldDef) -> bool {
};
}
lazy_static! {
static ref DEFAULT_FIELDS: HashMap<&'static str, &'static str> = HashMap::from([
static ref DEFAULT_FIELDS: FxHashMap<&'static str, &'static str> = FxHashMap::from_iter([
field!(scope_id: Cell<Option<ScopeId>>),
field!(symbol_id: Cell<Option<SymbolId>>),
field!(reference_id: Cell<Option<ReferenceId>>),
Expand Down
7 changes: 4 additions & 3 deletions tasks/ast_tools/src/generators/visit.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
use std::{borrow::Cow, collections::HashMap};
use std::borrow::Cow;

use convert_case::{Case, Casing};
use itertools::Itertools;
use proc_macro2::TokenStream;
use quote::{format_ident, quote, ToTokens};
use rustc_hash::FxHashMap;
use syn::{parse_quote, Ident};

use super::define_generator;
Expand Down Expand Up @@ -135,12 +136,12 @@ struct VisitBuilder<'a> {

visits: Vec<TokenStream>,
walks: Vec<TokenStream>,
cache: HashMap<Ident, [Option<Cow<'a, Ident>>; 2]>,
cache: FxHashMap<Ident, [Option<Cow<'a, Ident>>; 2]>,
}

impl<'a> VisitBuilder<'a> {
fn new(ctx: &'a LateCtx, is_mut: bool) -> Self {
Self { ctx, is_mut, visits: Vec::new(), walks: Vec::new(), cache: HashMap::new() }
Self { ctx, is_mut, visits: Vec::new(), walks: Vec::new(), cache: FxHashMap::default() }
}

fn build(mut self) -> (/* visits */ Vec<TokenStream>, /* walks */ Vec<TokenStream>) {
Expand Down
7 changes: 3 additions & 4 deletions tasks/ast_tools/src/passes/calc_layout.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use std::collections::HashMap;

use itertools::Itertools;
use lazy_static::lazy_static;
use quote::ToTokens;
use rustc_hash::FxHashMap;
use syn::Type;

use super::{define_pass, Pass};
Expand All @@ -18,7 +17,7 @@ use crate::{
#[cfg(not(target_pointer_width = "64"))]
compile_error!("This module only supports 64bit architectures.");

type WellKnown = HashMap<&'static str, PlatformLayout>;
type WellKnown = FxHashMap<&'static str, PlatformLayout>;

define_pass! {
pub struct CalcLayout;
Expand Down Expand Up @@ -279,7 +278,7 @@ fn calc_type_layout(ty: &TypeAnalysis, ctx: &EarlyCtx) -> Result<PlatformLayout>

macro_rules! well_known {
($($typ:ty: { $($platform:tt => $layout:expr,)*},)*) => {
WellKnown::from([
FxHashMap::from_iter([
$((
stringify!($typ),
well_known!(@ $( $platform => $layout,)*)
Expand Down
1 change: 1 addition & 0 deletions tasks/coverage/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ phf = { workspace = true, features = ["macros"] }
pico-args = { workspace = true }
rayon = { workspace = true }
regex = { workspace = true }
rustc-hash = { workspace = true }
saphyr = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
Expand Down
7 changes: 4 additions & 3 deletions tasks/coverage/src/typescript/meta.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! <https://github.com/microsoft/TypeScript/blob/6f06eb1b27a6495b209e8be79036f3b2ea92cd0b/src/harness/harnessIO.ts#L1237>

use std::{collections::HashMap, fs, path::Path, sync::Arc};
use rustc_hash::FxHashMap;
use std::{fs, path::Path, sync::Arc};

use oxc::{
allocator::Allocator,
Expand Down Expand Up @@ -35,7 +36,7 @@ pub struct CompilerSettings {
}

impl CompilerSettings {
pub fn new(options: &HashMap<String, String>) -> Self {
pub fn new(options: &FxHashMap<String, String>) -> Self {
Self {
modules: Self::split_value_options(options.get("module")),
targets: Self::split_value_options(options.get("target")),
Expand Down Expand Up @@ -93,7 +94,7 @@ impl TestCaseContent {
/// These files start with `// @<option-name>: <option-value>` and are followed by the file's content.
/// This function extracts the individual files with their content and drops unsupported files.
pub fn make_units_from_test(path: &Path, code: &str) -> Self {
let mut current_file_options: HashMap<String, String> = HashMap::default();
let mut current_file_options: FxHashMap<String, String> = FxHashMap::default();
let mut current_file_name: Option<String> = None;
let mut test_unit_data: Vec<TestUnitData> = vec![];
let mut current_file_content = String::new();
Expand Down
1 change: 1 addition & 0 deletions tasks/javascript_globals/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,5 @@ handlebars = { workspace = true }
oxc_tasks_common = { workspace = true }

lazy_static = { workspace = true }
rustc-hash = { workspace = true }
serde = { workspace = true, features = ["derive"] }
31 changes: 15 additions & 16 deletions tasks/javascript_globals/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
#![allow(clippy::print_stdout, clippy::print_stderr)]
use std::collections::HashMap;

use lazy_static::lazy_static;
use oxc_tasks_common::agent;
use rustc_hash::FxHashMap;
use serde::Serialize;
mod template;

Expand Down Expand Up @@ -30,10 +29,10 @@ impl<'a> Context<'a> {
}

fn get_diff(
current: &HashMap<String, bool>,
prev: &HashMap<String, bool>,
) -> HashMap<String, bool> {
let mut retv: HashMap<String, bool> = HashMap::new();
current: &FxHashMap<String, bool>,
prev: &FxHashMap<String, bool>,
) -> FxHashMap<String, bool> {
let mut retv: FxHashMap<String, bool> = FxHashMap::default();

for (key, value) in current {
if !prev.contains_key(key) {
Expand All @@ -45,22 +44,22 @@ fn get_diff(
}

lazy_static! {
static ref NEW_GLOBALS_2017: HashMap<String, bool> = {
return HashMap::from([
static ref NEW_GLOBALS_2017: FxHashMap<String, bool> = {
return FxHashMap::from_iter([
(String::from("Atomics"), false),
(String::from("SharedArrayBuffer"), false),
]);
};
static ref NEW_GLOBALS_2020: HashMap<String, bool> = {
return HashMap::from([
static ref NEW_GLOBALS_2020: FxHashMap<String, bool> = {
return FxHashMap::from_iter([
(String::from("BigInt"), false),
(String::from("BigInt64Array"), false),
(String::from("BigUint64Array"), false),
(String::from("globalThis"), false),
]);
};
static ref NEW_GLOBALS_2021: HashMap<String, bool> = {
return HashMap::from([
static ref NEW_GLOBALS_2021: FxHashMap<String, bool> = {
return FxHashMap::from_iter([
(String::from("AggregateError"), false),
(String::from("FinalizationRegistry"), false),
(String::from("WeakRef"), false),
Expand All @@ -73,8 +72,8 @@ fn main() {
// A value of true indicates that the variable may be overwritten.
// A value of false indicates that the variable should be considered read-only.
// open globals.json file relative to current file
// let globals: HashMap<String, HashMap<String, bool>>;
let globals: HashMap<String, HashMap<String, bool>> = match agent()
// let globals: FxHashMap<String, FxHashMap<String, bool>>;
let globals: FxHashMap<String, FxHashMap<String, bool>> = match agent()
.get("https://raw.githubusercontent.com/sindresorhus/globals/main/globals.json")
.call()
{
Expand All @@ -88,7 +87,7 @@ fn main() {
let new_globals_2015 = get_diff(&globals["es2015"], &globals["es5"]);

let new_globals_2015_2017 = {
let mut map = HashMap::new();
let mut map = FxHashMap::default();
map.extend(new_globals_2015.clone());
map.extend(NEW_GLOBALS_2017.clone());
map
Expand Down Expand Up @@ -158,7 +157,7 @@ fn main() {
}
}

fn to_env_vars(env_var_map: &HashMap<String, bool>) -> Vec<EnvVar> {
fn to_env_vars(env_var_map: &FxHashMap<String, bool>) -> Vec<EnvVar> {
let mut result: Vec<EnvVar> = vec![];
for (key, value) in env_var_map {
result.push(EnvVar { name: key, writeable: *value });
Expand Down
1 change: 1 addition & 0 deletions tasks/minsize/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,4 @@ flate2 = { workspace = true }
oxc_tasks_common = { workspace = true }

humansize = { workspace = true }
rustc-hash = { workspace = true }
6 changes: 3 additions & 3 deletions tasks/minsize/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
#![allow(clippy::print_stdout, clippy::print_stderr)]
use std::{
collections::HashMap,
fs::File,
io::{self, Write},
};
Expand All @@ -13,6 +12,7 @@ use oxc_minifier::{CompressOptions, Minifier, MinifierOptions};
use oxc_parser::Parser;
use oxc_span::SourceType;
use oxc_tasks_common::{project_root, TestFile, TestFiles};
use rustc_hash::FxHashMap;

// #[test]
// #[cfg(any(coverage, coverage_nightly))]
Expand All @@ -28,7 +28,7 @@ pub fn run() -> Result<(), io::Error> {
let path = project_root().join("tasks/minsize/minsize.snap");

// Data copied from https://github.com/privatenumber/minification-benchmarks
let targets = HashMap::<&str, &str>::from_iter([
let targets = FxHashMap::<&str, &str>::from_iter([
("react.development.js", "23.70 kB"),
("moment.js", "59.82 kB"),
("jquery.js", "90.07 kB"),
Expand All @@ -43,7 +43,7 @@ pub fn run() -> Result<(), io::Error> {
("typescript.js", "3.49 MB"),
]);

let gzip_targets = HashMap::<&str, &str>::from_iter([
let gzip_targets = FxHashMap::<&str, &str>::from_iter([
("react.development.js", "8.54 kB"),
("moment.js", "19.33 kB"),
("jquery.js", "31.95 kB"),
Expand Down
1 change: 1 addition & 0 deletions tasks/rulegen/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,6 @@ convert_case = { workspace = true }
handlebars = { workspace = true }
lazy_static = { workspace = true }
regex = { workspace = true }
rustc-hash = { workspace = true }
serde = { workspace = true, features = ["derive"] }
ureq = { workspace = true }
6 changes: 3 additions & 3 deletions tasks/rulegen/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
#![allow(clippy::print_stdout, clippy::print_stderr, clippy::disallowed_methods)]
use std::{
borrow::Cow,
collections::HashMap,
fmt::{self, Display, Formatter},
};

Expand All @@ -18,6 +17,7 @@ use oxc_ast::{
};
use oxc_parser::Parser;
use oxc_span::{GetSpan, SourceType, Span};
use rustc_hash::FxHashMap;
use serde::Serialize;
use ureq::Response;

Expand Down Expand Up @@ -381,7 +381,7 @@ struct State<'a> {
source_text: &'a str,
valid_tests: Vec<&'a Expression<'a>>,
invalid_tests: Vec<&'a Expression<'a>>,
expression_to_group_comment_map: HashMap<Span, String>,
expression_to_group_comment_map: FxHashMap<Span, String>,
group_comment_stack: Vec<String>,
}

Expand All @@ -391,7 +391,7 @@ impl<'a> State<'a> {
source_text,
valid_tests: vec![],
invalid_tests: vec![],
expression_to_group_comment_map: HashMap::new(),
expression_to_group_comment_map: FxHashMap::default(),
group_comment_stack: vec![],
}
}
Expand Down

0 comments on commit 02d5637

Please sign in to comment.