Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: add bench case for cached source #147

Draft
wants to merge 7 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions Cargo.lock

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

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ rustc-hash = "2.1.0"
dashmap = "6.1.0"
memchr = "2.7.4"
itertools = "0.13"

ouroboros = "0.18.4"

codspeed-criterion-compat = { version = "2.7.2", default-features = false, optional = true }
static_assertions = "1.1.0"
Expand Down
41 changes: 41 additions & 0 deletions benches/bench.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,43 @@ fn benchmark_replace_large_minified_source(b: &mut Bencher) {
});
}

fn benchmark_source_for_replace_large_minified_source_with_cache(b: &mut Bencher) {
let antd_minify = SourceMapSource::new(SourceMapSourceOptions {
value: ANTD_MIN_JS,
name: "antd.min.js",
source_map: SourceMap::from_json(ANTD_MIN_JS_MAP).unwrap(),
original_source: None,
inner_source_map: None,
remove_original_source: false,
});
let mut replace_source = ReplaceSource::new(antd_minify);
replace_source.replace(107, 114, "exports", None);
replace_source.replace(130, 143, "'object'", None);
replace_source.replace(165, 172, "__webpack_require__", None);
replace_source.replace(173, 180, "/*! react */\"./node_modules/.pnpm/[email protected]/node_modules/react/index.js\"", None);
replace_source.replace(183, 190, "__webpack_require__", None);
replace_source.replace(191, 202, "/*! react-dom */\"./node_modules/.pnpm/[email protected][email protected]/node_modules/react-dom/index.js\"", None);
replace_source.replace(205, 212, "__webpack_require__", None);
replace_source.replace(213, 220, "/*! dayjs */\"./node_modules/.pnpm/[email protected]/node_modules/dayjs/dayjs.min.js\"", None);
replace_source.replace(363, 370, "exports", None);
replace_source.replace(373, 385, "exports.antd", None);
replace_source.replace(390, 397, "__webpack_require__", None);
replace_source.replace(398, 405, "/*! react */\"./node_modules/.pnpm/[email protected]/node_modules/react/index.js\"", None);
replace_source.replace(408, 415, "__webpack_require__", None);
replace_source.replace(416, 427, "/*! react-dom */\"./node_modules/.pnpm/[email protected][email protected]/node_modules/react-dom/index.js\"", None);
replace_source.replace(430, 437, "__webpack_require__", None);
replace_source.replace(438, 445, "/*! dayjs */\"./node_modules/.pnpm/[email protected]/node_modules/dayjs/dayjs.min.js\"", None);
replace_source.replace(494, 498, "this", None);
let replace_source = replace_source.boxed();

let concat_source = ConcatSource::new(vec![replace_source.clone(), replace_source]);
let cached = CachedSource::new(concat_source);

b.iter(|| {
cached.source();
});
}

fn benchmark_concat_generate_string_with_cache_as_key(b: &mut Bencher) {
let sms_minify = SourceMapSource::new(SourceMapSourceOptions {
value: HELLOWORLD_MIN_JS,
Expand Down Expand Up @@ -278,6 +315,10 @@ fn bench_rspack_sources(criterion: &mut Criterion) {
"concat_generate_string_as_key",
benchmark_concat_generate_string_as_key,
);
group.bench_function(
"source_for_replace_large_minified_source_with_cache",
benchmark_source_for_replace_large_minified_source_with_cache,
);
group.finish();
}

Expand Down
85 changes: 59 additions & 26 deletions src/cached_source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,58 +49,81 @@ use crate::{
/// "Hello World\nconsole.log('test');\nconsole.log('test2');\nHello2\n"
/// );
/// ```
pub struct CachedSource<T> {

pub struct CachedSource<T: 'static> {
inner: CachedSourceInner<T>,
}

#[ouroboros::self_referencing]
pub struct CachedSourceInner<T: 'static> {
inner: Arc<T>,
#[not_covariant]
#[borrows(inner)]
cached_rope: Arc<OnceLock<Rope<'this>>>,
cached_hash: Arc<OnceLock<u64>>,
cached_maps:
Arc<DashMap<MapOptions, Option<SourceMap>, BuildHasherDefault<FxHasher>>>,
}

impl<T: Source> CachedSource<T> {
fn get_rope(&self) -> &Rope<'_> {
self
.inner
.with(|cache| cache.cached_rope.get_or_init(|| cache.inner.rope()))
}
}

impl<T> CachedSource<T> {
/// Create a [CachedSource] with the original [Source].
pub fn new(inner: T) -> Self {
Self {
inner: Arc::new(inner),
cached_hash: Default::default(),
cached_maps: Default::default(),
inner: CachedSourceInner::new(
Arc::new(inner),
|_| Default::default(),
Default::default(),
Default::default(),
),
}
}

/// Get the original [Source].
pub fn original(&self) -> &T {
&self.inner
self.inner.borrow_inner()
}
}

impl<T: Source + Hash + PartialEq + Eq + 'static> Source for CachedSource<T> {
fn source(&self) -> Cow<str> {
self.inner.source()
Cow::Owned(self.get_rope().to_string())
}

fn rope(&self) -> Rope<'_> {
self.inner.rope()
self.get_rope().clone()
}

fn buffer(&self) -> Cow<[u8]> {
self.inner.buffer()
self.inner.borrow_inner().buffer()
}

fn size(&self) -> usize {
self.source().len()
}

fn map(&self, options: &MapOptions) -> Option<SourceMap> {
if let Some(map) = self.cached_maps.get(options) {
if let Some(map) = self.inner.borrow_cached_maps().get(options) {
map.clone()
} else {
let map = self.inner.map(options);
self.cached_maps.insert(options.clone(), map.clone());
let map = self.inner.borrow_inner().map(options);
self
.inner
.borrow_cached_maps()
.insert(options.clone(), map.clone());
map
}
}

fn to_writer(&self, writer: &mut dyn std::io::Write) -> std::io::Result<()> {
self.inner.to_writer(writer)
self.inner.borrow_inner().to_writer(writer)
}
}

Expand All @@ -114,7 +137,7 @@ impl<T: Source + Hash + PartialEq + Eq + 'static> StreamChunks
on_source: crate::helpers::OnSource<'_, 'a>,
on_name: crate::helpers::OnName<'_, 'a>,
) -> crate::helpers::GeneratedInfo {
let cached_map = self.cached_maps.entry(options.clone());
let cached_map = self.inner.borrow_cached_maps().entry(options.clone());
match cached_map {
Entry::Occupied(entry) => {
let source = self.rope();
Expand All @@ -138,7 +161,7 @@ impl<T: Source + Hash + PartialEq + Eq + 'static> StreamChunks
}
Entry::Vacant(entry) => {
let (generated_info, map) = stream_and_get_source_and_map(
&self.inner as &T,
self.inner.borrow_inner() as &T,
options,
on_chunk,
on_source,
Expand All @@ -153,19 +176,21 @@ impl<T: Source + Hash + PartialEq + Eq + 'static> StreamChunks

impl<T> Clone for CachedSource<T> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
cached_hash: self.cached_hash.clone(),
cached_maps: self.cached_maps.clone(),
}
// Self {
// inner: self.inner.clone(),
// cached_rope: Default::default(),
// cached_hash: self.cached_hash.clone(),
// cached_maps: self.cached_maps.clone(),
// }
todo!()
}
}

impl<T: Source + Hash + PartialEq + Eq + 'static> Hash for CachedSource<T> {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
(self.cached_hash.get_or_init(|| {
(self.inner.borrow_cached_hash().get_or_init(|| {
let mut hasher = FxHasher::default();
self.inner.hash(&mut hasher);
self.original().hash(&mut hasher);
hasher.finish()
}))
.hash(state);
Expand All @@ -174,7 +199,7 @@ impl<T: Source + Hash + PartialEq + Eq + 'static> Hash for CachedSource<T> {

impl<T: PartialEq> PartialEq for CachedSource<T> {
fn eq(&self, other: &Self) -> bool {
self.inner == other.inner
self.inner.borrow_inner() == other.inner.borrow_inner()
}
}

Expand All @@ -186,9 +211,12 @@ impl<T: std::fmt::Debug> std::fmt::Debug for CachedSource<T> {
f: &mut std::fmt::Formatter<'_>,
) -> Result<(), std::fmt::Error> {
f.debug_struct("CachedSource")
.field("inner", self.inner.as_ref())
.field("cached_hash", self.cached_hash.as_ref())
.field("cached_maps", &(!self.cached_maps.is_empty()))
.field("inner", self.inner.borrow_inner().as_ref())
.field("cached_hash", self.inner.borrow_cached_hash().as_ref())
.field(
"cached_maps",
&(!self.inner.borrow_cached_maps().is_empty()),
)
.finish()
}
}
Expand Down Expand Up @@ -236,7 +264,12 @@ mod tests {
source.map(&map_options);

assert_eq!(
*clone.cached_maps.get(&map_options).unwrap().value(),
*clone
.inner
.borrow_cached_maps()
.get(&map_options)
.unwrap()
.value(),
source.map(&map_options)
);
}
Expand Down
Loading
Loading