var cases = [
{ nx: undefined, ny: 12 },
{ ny: 12, nx: undefined },
{ nx: undefined, ny: undefined },
{ nx: 12, ny: 12 }
]
var style = { transform: null }
for (const {nx, ny} of cases) {
if (nx !== undefined || ny !== undefined) {
style.transform = nx !== undefined
? (ny !== undefined
? `translate(${nx}px, ${ny}px)`
: `translateX(${nx}px)`)
: `translateY(${ny}px)`;
}
}
for (const {nx, ny} of cases) {
const sx = nx !== undefined // state_x
const sy = ny !== undefined // state_y
const state =
(sx && ! sy ? 1 : 0)
| (sy && ! sx ? 2 : 0)
| (sx && sy ? 4 : 0)
| ( ! sx || ! sy ? 8 : 0)
switch (state) {
case 8: // neither
style.transform = ''
break
case 4: // both
style.transform = `translate(${nx}px, ${ny}px)`
break
case 2: // only y
style.transform = `translateY(${ny}px)`
break
case 1: // only x
style.transform = `translateX(${nx}px)`
break;
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Typical Code | |
Bit-shift |
Test name | Executions per second |
---|---|
Typical Code | 1295169.1 Ops/sec |
Bit-shift | 1732554.9 Ops/sec |
The benchmark tests the performance of two different approaches for transforming CSS attributes, specifically the transform
property that manipulates the position of an element in a web application. The two approaches compared are:
Typical Code: This approach uses conventional conditional logic to check if each of the two variables, nx
and ny
, are defined. Depending on their states, it constructs a transform
string using template literals.
Bit-shift: This method utilizes a bitwise operation to encapsulate the states of nx
and ny
into a single integer (state
). Different states represent various combinations of whether nx
and ny
are defined. A switch
statement then assigns the transform
property based on the calculated state
.
Typical Code:
Bit-shift:
Overall, when deciding between approaches, developers should weigh the importance of code maintainability against performance demands, especially in production environments where execution speed can significantly impact user experience.