<script src='https://cdnjs.cloudflare.com/ajax/libs/classnames/2.3.2/index.min.js'></script>
<script src='https://unpkg.com/clsx@1.2.1/dist/clsx.min.js'></script>
var str = 'style';
var obj = {
'style-2': true,
'style-3': false,
'style-4': true,
}
var arr = ['style-5', 'style-6']
function composeCssClass(values) {
let className = ''
for (let valueIndex = 0, valuesLength = values.length; valueIndex < valuesLength; valueIndex += 1) {
const value = values[valueIndex]
switch (true) {
case !value: {
continue
}
case typeof value === 'string':
case typeof value === 'number': {
className = className + (className && ' ') + value
continue
}
case Array.isArray(value): {
const valueFromArray = composeCssClass(value)
if (valueFromArray) {
className = className + (className && ' ') + valueFromArray
}
continue
}
case typeof value === 'object': {
for (const key in value) {
if (value[key]) {
className = className + (className && ' ') + key
}
}
continue
}
}
}
return className || undefined
}
let result = window.classNames(str, obj, arr, 'test classname')
let result = window.clsx(str, obj, arr, 'test classname')
let result = composeCssClass(str, obj, arr, 'test classname')
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
classnames | |
clsx | |
custom implemenatation |
Test name | Executions per second |
---|---|
classnames | 670237.6 Ops/sec |
clsx | 871176.1 Ops/sec |
custom implemenatation | 588902.5 Ops/sec |
Overview of the Benchmark
The provided JSON represents a JavaScript benchmark that compares three different approaches for combining CSS class names: classnames
, clsx
, and a custom implementation.
What is tested
The benchmark tests the performance of each approach in creating a string of concatenated CSS class names from an object (obj
) and an array (arr
). The custom implementation (composeCssClass
) uses a recursive approach to handle nested objects and arrays.
Options compared
composeCssClass
): A custom JavaScript function that uses recursion to handle nested objects and arrays.Pros and Cons of each approach
classnames
, requires more dependencies (CSSOM and CSSParser).composeCssClass
):Library analysis
Special JS feature or syntax
composeCssClass
implementation to concatenate class names.clsx
to parse CSS classes and handle them efficiently.Other alternatives
lodash.classNames
, react-classnames
, or cssclass
.Benchmark results
The latest benchmark results show that:
classnames
, and then the custom implementation (composeCssClass
).clsx
and classnames
is relatively small, but clsx
wins due to its optimization techniques.composeCssClass
) has a lower execution rate compared to clsx
and classnames
.Keep in mind that the benchmark results may vary depending on the input data size, device platform, and other factors.