sass-loader performance
We have a fairly expansive suite of sass files (around 600 files total). When running our suite directly with libsass, behind node-sass, it takes less than 5 seconds. Yet, sass-loader through webpack takes over 15 seconds.
I am wondering if others have run into this or if we can debug this to find where the performance lag lies.
I experienced great improvements after switching to node-sass. But doing that would go in opposite direction with component-based styling. @mmase do you have lots of variables and mixins that you import with @import? Also, are you importing .sass files multiple times, i.e, every component imports its own sass file?
"Also, are you importing .sass files multiple times, i.e, every component imports its own sass file?" would doing this improve or worsen the compiliation speed?
Related to: #307
@wildeyes i think so. I have 2 sass files, variables.sass and componentA.sass. The variables file is used by multiple components. Incremental rebuild speed for 700 components took 8 secs on a variable.sass change while 2 secs for componentA.sass.
Based on this discussion, I started profiling an example project yesterday and had some interesting insights. First of all, the sass-loader performance (49.2s) is completely unacceptable compared to fast-sass-loader (5.29s) or even bare node-sass (2.25s) from the command line. All three toolchains compile the same source code and produce similar output. We can expect some overhead coming from webpack since we need to initialize it, set up the loader pipeline, etc., but even the fast-sass-loader is unacceptable slow compared to bare node-sass in my opinion.
Overview
So let's take a look at the flame graphs:

First of all, as you can see, node-sass is spending most of the time outside of Node.js which is what we expected, since the hard work is done by Libsass.
Now, let's take a look at both sass-loaders. The execution can roughly be divided into five phases (indicated as black boxes in the graph) that I will discuss in detail later:
- webpack initialization
- first execution sass-loader
- first execution css-loader
- second execution sass-loader (this block is not visible in the fast-sass-loader graph, reasons below)
- second execution css-loader
So, the first surprise here is that we have two separate compilations going on. This is due to the extract-text-webpack-plugin which initiates a child compilation. Tbh, I'm not sure why this is necessary at all. @sokra can give us more insights here.
The second surprise is, that the second compilation doesn't use the cache from the first compilation. In the sass-loader graph, you can clearly see that the second pass takes almost exactly the same amount of time. This could be improved a little bit because the sass-loader is currently not using webpack's fs cache, but that would only reduce the second sass-loader execution time (4.), which is not where most of the time is spent.
The most time, however, is spent—and that's the third surprise—inside the css-loader. You can clearly see that in both graphs. It takes up half of the total time in the fast-sass-loader setup, and even more in the sass-loader setup.
It might also be surprising that node-sass and webpack + fast-sass-loader take almost the same amount of time to compile. In the flame graphs, you can clearly see that node-sass finishes almost at the same time where the 2. block of the fast-sass-loader graph ends. However, we need to remember that the fast-sass-loader is deduping all files before compilation, so there's far less to compile.
Now, let's take a look at all the phases in detail.
Phase 1: Webpack initialization & loader execution start

No big surprise here: The initialization of both setups takes almost the same amount of time. Differences here are probably due to I/O or general OS flakyness because there is no actual difference between both loaders here.
You can clearly see that during the first 1000ms, most of the time is spent requiring modules. That's why webpack almost always takes at least 1s to compile—even with the simplest setup. Maybe we could win something here with lazy requiring ala lazy-req.
Phase 2: Import resolving & sass compilation (1. compilation)

Now that looks different!
First, let's look at the sass-loader: The sass-loader registers a custom importer and kicks off the compilation. Now, we're essentially waiting for Libsass to call back. You can clearly see that there is a lot of back-and-forth going on with recurring breaks (grey bars) where the process is just sitting and waiting for Libsass. This graph led me to the assumption that Libsass might be doing sequential I/O. Concurrent I/O would look different, I suppose. After all the resolving is done, Libsass is performing the actual compilation and we're just waiting for Libsass to call back. Nothing to optimize here.
Now, let's look at the fast-sass-loader: The fast-sass-loader preparses the source code with regexps for import statements and passes all imports to webpack's resolver. After the import paths have been resolved, the imported files are read from disk via node's fs module and then replaced with their import statements. Duplicated imports are simply omitted, only the first occurence gets included. This is way faster than the sass-loader, which shows that webpack's resolver is not the bottleneck. In fact, it's really fast and almost negligible in the graph.
The actual Sass compilation is also a lot faster since a lot of imports have been deduped. It's just that Libsass has less to parse.
Phase 3: css-loader (1. compilation)

This phase is the most interesting one because:
- it takes up most of the time
- there is nothing the sass-loader or the fast-sass-loader can do
The only difference is that the amount of data is very different. The fast-sass-loader produces a string with length 627067, the sass-loader with 6914854. This is 11 times longer. And this translates roughly to the amount of time. The css-loader takes 11 times longer processing the output from the sass-loader.
There are two things that I found surprising:
-
Why does the css-loader take so long? In this case, it is only required to translate the CSS into a CommonJS module while transforming all
url()statements and remaining@importintorequire(). To me, this task seems a lot more trivial than the Sass compilation. The funny thing is: We're spending 9.6s just inside postcss-modules-local-by-default during the first compilation. In total, we're spending 16.29s there – and we didn't even ask for CSS modules... And that's just the first postcss plugin. The thread is completely busy for 13s in the first compilation while processing postcss plugins without any chance for other tasks. In total: 26s just inside postcss, hogging the CPU. -
Why is postcss busy with generating source maps? We didn't ask for source maps... then I took a look at the css-loader: This call applies the
mapoption irregardless of aninputMap. In fact,inputMapis undefined in this case, but we're still telling postcss to generate a map. As an experiment, I setmap: falseand was able to shave off 10s in total—just by setting one flag. It's still crazy that source maps take up 10s. Switching source maps on and off with node-sass makes a difference of 150ms.
Phase 4: sass-loader & css-loader (2. compilation)

The sass-loader performs exactly the same compilation again. No results from the first compilation are re-used.
The fast-sass-loader skips the second Sass compilation because it uses its own cache. That's a nice shortcut, but this should be fixed in webpack.
I don't understand why we need a second compilation. And if we need the second one, can't we just skip the first one? This seems redundant.
Conclusion
- We spend 1s just requiring webpack modules and loaders and initializing the loader pipeline. This could possibly be improved with a tool like lazy-req.
- The sass-loader could be improved by:
- preparsing and resolving all dependencies. While this might seem like a good idea, there are also problems: 1. The source maps will be incorrect. 2. Errors won't be reported at the correct location. It all boils down to the fact that Libsass doesn't know the original location of the source anymore.
- using the webpack cache when resolving the file. A custom importer is also allowed to pass the actual source to Libsass. This way, we could use webpack's internal fs caching layer.
- deduping dependencies. This could be achieved by passing an empty string if the custom importer has resolved a resource for the second time. While this operation is not entirely safe, it will most likely do more good than bad in most cases. I'd say: if the specificity relies on the correct source order, there's a bigger problem.
- The css-loader could be improved by:
- using a simpler pipeline for CSS files that are not CSS modules. This performance penalty is not acceptable.
- only generating source maps when they are actually requested
- "somehow" improving the postcss pipeline. Blocking the process for 13s is not acceptable, even for CSS modules. I don't know how we can improve that. Maybe postcss is applying the plugins in an unfortunate way?
- The extract-text-webpack-plugin could be improved by:
- getting rid of the second compilation
- or using cached loader results where possible
Here are both CPU profiles. Load them into your Chrome Developer Tools if you want to take a look for yourself.
This was bothering me for a long time because I think we can do a lot better than that :grin:
As comparison, the sass-loader setup with [email protected] takes 10.1s and looks like this:
As @sokra pointed out: With the allChunks: true option...
new ExtractTextPlugin({
filename: '[name].css',
allChunks: true
})
the second compilation can be skipped:

thus reducing the built time to 23.9s
@jhnns Hi jhnns, may I ask what tools you were using to generate those profiling screenshots? I need to troubleshoot webpack issues as well, I need a tool to help me pinpoint the problem.
Run
node --inspect-brk ./node_modules/.bin/webpack
to start the debugging process. The process will halt at the first line and print a debugger URL. Copy the debugger URL into the Chrome Browser and the developers tools will initialize.
Then go to the JavaScript profiler tab and start profiling :) After you've pressed stop, the flame graph will be generated.
If you don't want to copy debugger URLs around, you can also use the NIM chrome extension. It discovers debuggable node processes automatically.
@jhnns thank you very much!!!
Not directly related to this thread, but also interesting: Looks like the most recent v8 version (with their new optimizing compiler TurboFan) gives a startup performance boost of 160% (1150ms vs 720ms).
Using v8/node, phase 1 looks like this:

The overall build time decreased from 49.2s to 41.35s (~119% faster).
TurboFan doesn't bail out on try/catch which will probably improve the startup performance of all node applications because node is using try/catch to initialize the modules.
awesome 👍
Postcss issue about source map: https://github.com/postcss/postcss-loader/issues/195
After disabling generation of source maps using my PR https://github.com/webpack-contrib/css-loader/issues/478 i get about ~1.5x-2x speedup my build
hello friends. Just as an FYI, I'm looking into this. With any luck, we'll see if there is any low hanging fruit to go after besides for the allChunks and sourcemap: false optimizations.
any new updates? @mikesherov
@levin-du, several of css-loaders dependencies are extremely slow but have been rewritten to be much much faster, but are semver major. css-loader is currently undergoing a rewrite along with the rest of the CSS module loading architecture, so I asked if a patch would be accepted. Due to the fact that it's a major bump, I was asked to wait for the rewrite to be completed instead.
That's a shame, @mikesherov, but thanks for the update!
Maybe dart-sass #435 is faster. I need to try that out.
:wave: Hi, I'm the LibSass and Node Sass maintainer.
I get pinged about sass-loader issues on occasion and wanted to add some clarity around how Node Sass and LibSass work.
The fast-sass-loader preparses the source code with regexps for import statements [...] Duplicated imports are simply omitted, only the first occurence gets included.
While this might seem like a good idea, there are also problems: 1. The source maps will be incorrect. 2. Errors won't be reported at the correct location.
deduping dependencies. This could be achieved by passing an empty string if the custom importer has resolved a resource for the second time. While this operation is not entirely safe, it will most likely do more good than bad in most cases. I'd say: if the specificity relies on the correct source order, there's a bigger problem.
Internally LibSass will only resolve the first unique instance of an @import. So this de-duping behaviour is already happening.
I believe this applies to custom importers as well (should be easy enough to confirm). Assuming this is the case import order will always what is authored.
This graph led me to the assumption that Libsass might be doing sequential I/O. Concurrent I/O would look different, I suppose.
The IO is 100% controlled by Node Sass, and the libuv event loop. When render is called Node Sass queue a LibSass job in the uv event loop, and uv pings Node Sass back when the work is done with the output (as JSON blog is the output and statistics). This is how all callbacks work, nothing special going.
When a custom importer is used an additional step happens. When LibSass encounters an @import it calls each registered custom importer sequentially until one of them returns with a value. Executing a custom function (when defined in JavaScript) means the LibSass process "pauses" compilation to tell Node Sass to execute the custom importer. Node pushes the import function into the uv event loop, uv eventually executes it, and passes the resulting value to Node Sass. Node Sass then passes the value back to LibSass which continues parsing.
This back and fourth is what you're seeing in that flame graph. Everything is happening asynchronously. Each LibSass process is isolated, and Node is in change of how parallel the work is.
I assume that the threadpool issue with custom importers #147 is the cause for the performance problems #296. (https://github.com/webpack-contrib/sass-loader/pull/558#issuecomment-384263644)
I've seen this comment pop up a few times so I wanted to include it here.
The thread pool here is that the uv event loop I mentioned above. The thread pool issue is result of the thread pool being exhausted. This happens if lots of importers are being resolved in parallel and they're additionally doing asynchronous work that requires the thread pool i.e. fs.readFile.
This is well documented in https://github.com/sass/node-sass/issues/857.
Using some kind in memory fs cache could certainly work around this problem.
Maybe dart-sass #435 is faster. I need to try that out.
This isn't likely to be the case. You can give it a shot yourself with this branch of the postcss benchmark repo - https://github.com/postcss/benchmark/pull/8
The LibSass team has publicly noted there has been little to no effort put into performance, instead prioritising spec compliance and features. With features largely stabilised with 3.5 it will only be getting faster from here.
Having looked though your analysis in https://github.com/webpack-contrib/sass-loader/issues/296#issuecomment-288464857 it's not clear to me that node-sass is the bottle neck.
Looks like most of the time is webpack and surrounding ecosystem loaders, however I frequently see Node Sass stated as the cause. Is there anything specifically you think Node Sass or LibSass could address?