<script src='https://cdnjs.cloudflare.com/ajax/libs/classnames/2.2.6/index.min.js'></script>
<script src='https://unpkg.com/clsx@1.1.1/dist/clsx.min.js'></script>
<script src="https://cdn.jsdelivr.net/npm/@emotion/css@11.13.4/dist/emotion-css.umd.min.js"></script>
var c = {
a: true,
b: false,
c: undefined,
d: "lorem-ipsum"
};
var someClasses = ['class1', true || 'class2', false && 'class3', true ? 'class4' : 'class5', c]
let result = window.classNames(someClasses)
let result = window.clsx(someClasses)
let result = window.emotion.cx(someClasses)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
classnames | |
clsx | |
cx |
Test name | Executions per second |
---|---|
classnames | 5501915.0 Ops/sec |
clsx | 14447509.0 Ops/sec |
cx | 2760250.5 Ops/sec |
The benchmark under discussion compares three different approaches to manipulating CSS class names in JavaScript: classnames, clsx, and cx (from Emotion). Each of these libraries provides a way to dynamically construct class name strings based on certain conditions, but they have different implementations, performance characteristics, and usability.
classnames: This is a popular utility that allows developers to conditionally join class names together. It supports various input types, allowing for both string and object inputs where keys are class names and values are booleans indicating whether the class should be included.
clsx: This library is a smaller and more lightweight alternative to classnames. It is optimized for performance and also allows for conditional class name generation, but it’s designed to have a simpler and more efficient code base, making it more performant than classnames in many cases.
cx (from Emotion): cx is part of the Emotion library, which is designed for writing CSS styles with JavaScript. The cx function allows for conditional application of class names, similar to the other two libraries, but it may also be integrated with Emotion's styling capabilities.
The benchmark compares the execution speed of these three methods by running a set of conditions against an object c
and a predefined array of classes:
var c = {
a: true,
b: false,
c: undefined,
d: "lorem-ipsum"
};
var someClasses = ['class1', true || 'class2', false && 'class3', true ? 'class4' : 'class5', c];
Here, the someClasses
variable serves as input, combining strings, boolean expressions, and an object, creating various potential class names dynamically.
The benchmark results show the number of executions per second for each method:
classnames:
clsx:
cx (from Emotion):
When choosing between these libraries, considerations include:
Other alternatives for conditional class names include:
In conclusion, the choice of which library to use should consider the specific demands of your project, coding style preferences, and performance requirements. Each of these libraries provides a robust solution for dynamically building class names but shines under different contexts.