Skip to content

Commit

Permalink
perf: use rustc-hash
Browse files Browse the repository at this point in the history
  • Loading branch information
xusd320 committed Feb 5, 2024
1 parent 544c3b7 commit 0ce07cd
Show file tree
Hide file tree
Showing 52 changed files with 220 additions and 205 deletions.
8 changes: 1 addition & 7 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/core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ convert_case = "0.6.0"
path-clean = "1.0.1"
sailfish = "0.8.3"
merge-source-map = "1.2.0"
rustc-hash = "1.1.0"

[features]
profile = ["dep:eframe", "dep:puffin", "dep:puffin_egui"]
32 changes: 32 additions & 0 deletions crates/core/src/collections.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
pub use rustchash::{FxHashMap as HashMap, FxHashSet as HashSet};

mod rustchash {
use std::collections::{HashMap, HashSet};
use std::hash::BuildHasherDefault;

use rustc_hash::FxHasher;

pub type FxRandomState = BuildHasherDefault<FxHasher>;

pub type FxHashMap<K, V> = HashMap<K, V, FxRandomState>;

pub type FxHashSet<V> = HashSet<V, FxRandomState>;
}

#[macro_export(local_inner_macros)]
macro_rules! hashmap {
(@single $($x:tt)*) => (());
(@count $($rest:expr),*) => (<[()]>::len(&[$(hashmap!(@single $rest)),*]));

($($key:expr => $value:expr,)+) => { hashmap!($($key => $value),+) };
($($key:expr => $value:expr),*) => {
{
let _cap = hashmap!(@count $($key),*);
let mut _map = $crate::collections::HashMap::default();
$(
let _ = _map.insert($key, $value);
)*
_map
}
};
}
2 changes: 2 additions & 0 deletions crates/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ pub use {
tracing_subscriber, tungstenite, twox_hash,
};

pub mod collections;

#[macro_export]
macro_rules! mako_profile_scope {
($id:expr) => {
Expand Down
1 change: 0 additions & 1 deletion crates/mako/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ glob-match = "0.2.1"

[dev-dependencies]
insta = { version = "1.30.0", features = ["yaml"] }
maplit = "1.0.2"
testing = "0.35.10"
swc_ecma_transforms_testing = "0.136.2"

Expand Down
12 changes: 6 additions & 6 deletions crates/mako/src/build.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::sync::mpsc::Sender;
use std::sync::Arc;
use std::time::Instant;

use cached::proc_macro::cached;
use mako_core::anyhow::{anyhow, Result};
use mako_core::collections::{HashMap, HashSet};
use mako_core::colored::Colorize;
use mako_core::lazy_static::lazy_static;
use mako_core::rayon::ThreadPool;
Expand Down Expand Up @@ -82,7 +82,7 @@ impl Compiler {
pub fn build_tasks(&self, tasks: Vec<Task>, with_cache: bool) -> Result<HashSet<ModuleId>> {
debug!("build tasks: {:?}", tasks);
if tasks.is_empty() {
return Ok(HashSet::new());
return Ok(HashSet::default());
}

let (pool, rs, rr) = create_thread_pool::<Result<(Module, ModuleDeps, Task)>>();
Expand All @@ -99,7 +99,7 @@ impl Compiler {
}

let mut errors = vec![];
let mut module_ids = HashSet::new();
let mut module_ids = HashSet::default();
for r in rr {
count -= 1;
match r {
Expand Down Expand Up @@ -279,7 +279,7 @@ module.exports = new Promise((resolve, reject) => {{
raw: code,
raw_hash: 0,
resolved_resource: Some(resource.clone()),
missing_deps: HashMap::new(),
missing_deps: HashMap::default(),
ignored_deps: vec![],
top_level_await: false,
is_async: has_script,
Expand Down Expand Up @@ -342,7 +342,7 @@ module.exports = new Promise((resolve, reject) => {{
// resolve
let mut dep_resolve_err = None;
let mut dependencies_resource = Vec::new();
let mut missing_deps = HashMap::new();
let mut missing_deps = HashMap::default();
let mut ignored_deps = Vec::new();

for dep in deps {
Expand Down Expand Up @@ -370,7 +370,7 @@ module.exports = new Promise((resolve, reject) => {{
let source = e.1;
let span = e.3;
// 使用 hasMap 记录循环依赖
let mut target_map: HashMap<String, i32> = HashMap::new();
let mut target_map: HashMap<String, i32> = HashMap::default();
target_map.insert(target, 1);

let mut err = format!("Module not found: Can't resolve '{}'", source);
Expand Down
4 changes: 2 additions & 2 deletions crates/mako/src/chunk_graph.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::collections::{HashMap, HashSet};
use std::hash::Hasher;

use mako_core::collections::{HashMap, HashSet};
use mako_core::petgraph::stable_graph::{DefaultIx, NodeIndex, StableDiGraph};
use mako_core::petgraph::visit::Dfs;
use mako_core::petgraph::Direction;
Expand All @@ -19,7 +19,7 @@ impl ChunkGraph {
pub fn new() -> Self {
Self {
graph: StableDiGraph::new(),
id_index_map: HashMap::new(),
id_index_map: HashMap::default(),
}
}

Expand Down
2 changes: 1 addition & 1 deletion crates/mako/src/chunk_pot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ mod ast_impl;
mod str_impl;
pub mod util;

use std::collections::HashMap;
use std::sync::Arc;
use std::vec;

use mako_core::anyhow::Result;
use mako_core::collections::HashMap;
use mako_core::indexmap::IndexSet;
use mako_core::swc_css_ast::Stylesheet;
use mako_core::ternary;
Expand Down
2 changes: 1 addition & 1 deletion crates/mako/src/chunk_pot/ast_impl.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use std::collections::HashMap;
use std::sync::Arc;

use cached::proc_macro::cached;
use mako_core::anyhow::Result;
use mako_core::cached::SizedCache;
use mako_core::collections::HashMap;
use mako_core::swc_common::{Mark, DUMMY_SP, GLOBALS};
use mako_core::swc_css_ast::Stylesheet;
use mako_core::swc_css_codegen::writer::basic::{BasicCssWriter, BasicCssWriterConfig};
Expand Down
8 changes: 2 additions & 6 deletions crates/mako/src/chunk_pot/str_impl.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use std::collections::HashMap;
use std::sync::Arc;

use cached::proc_macro::cached;
use mako_core::anyhow::{anyhow, Result};
use mako_core::cached::SizedCache;
use mako_core::collections::HashMap;
use mako_core::rayon::prelude::*;
use mako_core::swc_ecma_codegen::text_writer::JsWriter;
use mako_core::swc_ecma_codegen::{Config as JsCodegenConfig, Emitter};
Expand Down Expand Up @@ -223,11 +223,7 @@ fn pot_to_chunk_module_object_string(pot: &ChunkPot, context: &Arc<Context>) ->
let sorted_kv = {
mako_core::mako_profile_scope!("collect_&_sort");

let mut sorted_kv = pot
.module_map
.iter()
.map(|(k, v)| (k, v))
.collect::<Vec<_>>();
let mut sorted_kv = pot.module_map.iter().collect::<Vec<_>>();

if context.config.hash {
sorted_kv.sort_by_key(|(k, _)| *k);
Expand Down
10 changes: 3 additions & 7 deletions crates/mako/src/chunk_pot/util.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::sync::Arc;

use cached::proc_macro::cached;
use mako_core::anyhow::{anyhow, Result};
use mako_core::cached::SizedCache;
use mako_core::collections::HashMap;
use mako_core::sailfish::TemplateOnce;
use mako_core::swc_common::DUMMY_SP;
use mako_core::swc_ecma_ast::{
Expand Down Expand Up @@ -127,7 +127,7 @@ where
K: Hash + Eq + Ord,
V: Hash,
{
let mut sorted_kv = map.iter().map(|(k, v)| (k, v)).collect::<Vec<_>>();
let mut sorted_kv = map.iter().collect::<Vec<_>>();
sorted_kv.sort_by_key(|(k, _)| *k);

let mut hasher: XxHash64 = Default::default();
Expand Down Expand Up @@ -160,11 +160,7 @@ pub(super) fn to_array_lit(elems: Vec<ExprOrSpread>) -> ArrayLit {
pub(crate) fn pot_to_module_object(pot: &ChunkPot, context: &Arc<Context>) -> Result<ObjectLit> {
mako_core::mako_profile_function!();

let mut sorted_kv = pot
.module_map
.iter()
.map(|(k, v)| (k, v))
.collect::<Vec<_>>();
let mut sorted_kv = pot.module_map.iter().collect::<Vec<_>>();
sorted_kv.sort_by_key(|(k, _)| *k);

let mut props = Vec::new();
Expand Down
10 changes: 5 additions & 5 deletions crates/mako/src/compiler.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use std::collections::HashMap;
use std::fs;
use std::path::PathBuf;
use std::sync::{Arc, Mutex, RwLock};
use std::time::{Instant, UNIX_EPOCH};

use mako_core::anyhow::{anyhow, Error, Result};
use mako_core::collections::HashMap;
use mako_core::colored::Colorize;
use mako_core::regex::Regex;
use mako_core::swc_common::sync::Lrc;
Expand Down Expand Up @@ -50,7 +50,7 @@ pub struct MemoryChunkFileCache {
impl MemoryChunkFileCache {
pub fn new(root: Option<PathBuf>) -> Self {
Self {
content_map: HashMap::new(),
content_map: HashMap::default(),
root,
}
}
Expand Down Expand Up @@ -119,7 +119,7 @@ impl Default for Context {
root: PathBuf::from(""),
module_graph: RwLock::new(ModuleGraph::new()),
chunk_graph: RwLock::new(ChunkGraph::new()),
assets_info: Mutex::new(HashMap::new()),
assets_info: Mutex::new(HashMap::default()),
modules_with_missing_deps: RwLock::new(Vec::new()),
meta: Meta::new(),
plugin_driver: Default::default(),
Expand Down Expand Up @@ -271,7 +271,7 @@ impl Compiler {

if let Some(minifish_config) = &config._minifish {
let inject = if let Some(inject) = &minifish_config.inject {
let mut map = HashMap::new();
let mut map = HashMap::default();

for (k, ii) in inject.iter() {
let exclude = if let Some(exclude) = &ii.exclude {
Expand Down Expand Up @@ -342,7 +342,7 @@ impl Compiler {
root,
module_graph: RwLock::new(ModuleGraph::new()),
chunk_graph: RwLock::new(ChunkGraph::new()),
assets_info: Mutex::new(HashMap::new()),
assets_info: Mutex::new(HashMap::default()),
modules_with_missing_deps: RwLock::new(Vec::new()),
meta: Meta::new(),
plugin_driver,
Expand Down
4 changes: 2 additions & 2 deletions crates/mako/src/config.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use std::collections::HashMap;
use std::fmt;
use std::hash::Hasher;
use std::path::{Path, PathBuf};

use mako_core::anyhow::{anyhow, Result};
use mako_core::clap::ValueEnum;
use mako_core::collections::HashMap;
use mako_core::colored::Colorize;
use mako_core::regex::Regex;
use mako_core::serde::{Deserialize, Deserializer};
Expand Down Expand Up @@ -729,7 +729,7 @@ impl Config {
let target = config.targets.get("node").unwrap_or(&14.0);

// set target to node version
config.targets = HashMap::from([("node".into(), *target)]);
config.targets = HashMap::from_iter([("node".into(), *target)]);

// ignore standard library
config
Expand Down
2 changes: 1 addition & 1 deletion crates/mako/src/generate.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use std::collections::HashSet;
use std::fs;
use std::ops::DerefMut;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Duration, Instant};

use mako_core::anyhow::{anyhow, Result};
use mako_core::collections::HashSet;
use mako_core::indexmap::IndexSet;
use mako_core::rayon::prelude::*;
use mako_core::serde::Serialize;
Expand Down
6 changes: 3 additions & 3 deletions crates/mako/src/generate_chunks.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use std::collections::HashMap;
use std::path::Path;
use std::sync::Arc;
use std::time::Instant;
use std::vec;

use mako_core::anyhow::{anyhow, Result};
use mako_core::collections::HashMap;
use mako_core::indexmap::IndexSet;
use mako_core::swc_common::DUMMY_SP;
use mako_core::swc_css_ast::Stylesheet;
Expand Down Expand Up @@ -187,8 +187,8 @@ impl Compiler {
fn chunk_maps(
non_entry_chunk_files: &[ChunkFile],
) -> (HashMap<String, String>, HashMap<String, String>) {
let mut js_chunk_map: HashMap<String, String> = HashMap::new();
let mut css_chunk_map: HashMap<String, String> = HashMap::new();
let mut js_chunk_map: HashMap<String, String> = HashMap::default();
let mut css_chunk_map: HashMap<String, String> = HashMap::default();

for f in non_entry_chunk_files.iter() {
match f.file_type {
Expand Down
2 changes: 1 addition & 1 deletion crates/mako/src/group_chunk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ impl Compiler {
mako_core::mako_profile_function!();
debug!("group_chunk");

let mut visited = HashSet::new();
let mut visited = HashSet::default();
let mut edges = vec![];
let module_graph = self.context.module_graph.read().unwrap();
let mut chunk_graph = self.context.chunk_graph.write().unwrap();
Expand Down
2 changes: 1 addition & 1 deletion crates/mako/src/module.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use std::collections::{HashMap, HashSet};
use std::fmt::{Debug, Formatter};
use std::path::PathBuf;
use std::sync::Arc;

use mako_core::anyhow::{anyhow, Result};
use mako_core::base64::engine::{general_purpose, Engine};
use mako_core::collections::{HashMap, HashSet};
use mako_core::pathdiff::diff_paths;
use mako_core::swc_common::{Span, DUMMY_SP};
use mako_core::swc_ecma_ast::{BlockStmt, FnExpr, Function, Module as SwcModule};
Expand Down
Loading

0 comments on commit 0ce07cd

Please sign in to comment.