Name mangling for performance
Today I learned about name mangling, which is an approach to making sure all your variables, functions, and other entities have unique names. You may have seen a bunch of randomized CSS class names on sites like Twitter (RIP) and Facebook, this is name mangling in action.
I had previously thought this was an obfuscation approach to fool ad blockers, but now I think that’s an unintentional benefit.
When developing for the web, name mangling can:
- reduce function and variable collisions in JavaScript
- reduce class name and ID collisions in CSS
- provide a way to bust browser caches
- indirectly reduce conflicts caused by browser extensions and third-party scripts
Name mangling is crucial for non-scoped component frameworks, but there are performance benefits as well. By renaming your identifiers during a build process, you can save bytes by using shorter identifiers and still have descriptive names while developing.
Sometimes these byte savings are significant: The VS Code team recently reduced the size of their shipped JavaScript by 20% using name mangling.
I don’t think name mangling is necessary outside of a web app, and the end result is frustrating to debug. For example, if you have an issue that only appears as a result of name mangling, or if you’re a browser extension developer trying to extend the functionality of a site. But it’s a good tool for the toolbox.