var str='Стэн против сил зла (2 сезон 1-8 серия из 8) (2017) WEB-DL 720p | Newstudio [AVC]';
var e = function (str) {
if (str) return str.
replace(/&/g, '&').
replace(/</g, '<').
replace(/>/g, '>').
replace(/"/g, '"').
replace(/'/g, ''');
return '';
};
var e2 = function (str) {
if (str) return str
.split('&').join('&')
.split('<').join('<')
.split('>').join('>')
.split('"').join('"')
.split("'").join(''');
return '';
};
var r = [/&/g,/</g,/>/g,/"/g,/'/g]
var e3 = function (str) {
if (str) return str.
replace(r[0], '&').
replace(r[1], '<').
replace(r[2], '>').
replace(r[3], '"').
replace(r[4], ''');
return '';
};
e(str);
e2(str);
e3(str);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
a | |
b | |
c |
Test name | Executions per second |
---|---|
a | 1278249.2 Ops/sec |
b | 608406.7 Ops/sec |
c | 864114.8 Ops/sec |
Benchmark Explanation
The provided benchmark tests the performance difference between three approaches for encoding and decoding HTML special characters:
e(str)
: This function uses replace()
with multiple character replacements (ampersand, less-than, greater-than, double quotes, and single quotes) to encode the input string.e2(str)
: This function splits the input string into substrings using each special character as a delimiter (&
, <
, >
, "
, and '
) and then joins them back together with the corresponding encoded characters.e3(str)
: This function uses an array of regular expressions to replace each special character individually.Options Compared
The benchmark compares the performance of these three approaches on a given input string, which contains HTML special characters. The test aims to determine which approach is faster and more efficient.
Pros and Cons of Each Approach:
e(str)
: This approach is simple and straightforward but may be slower due to the multiple replace()
calls.e2(str)
: This approach involves splitting and joining substrings, which can lead to string concatenation overhead.e3(str)
: This approach uses regular expressions to replace special characters individually.e(str)
for larger input strings, allows for efficient encoding/decoding using a single pass.Library Usage
There is no explicit library usage in the provided benchmark code. However, it's worth noting that some browsers (like Safari) have built-in functions for HTML escaping (e.g., String.prototype.replace()
with a regex pattern).
Special JS Features/Syntax
The benchmark does not explicitly use any special JavaScript features or syntax beyond regular expressions and string manipulation.
Alternative Approaches
Other approaches to encoding/decoding HTML special characters could include:
template literals: "Hello ${ampersand} World!"
) for HTML escaping.Keep in mind that these alternatives may have different performance characteristics, trade-offs, and use cases depending on the specific requirements of your project.