var toEscape = `ab<div id="a" class='sasa'>asa</div>`;
var result = '';
var div = document.createElement('div');
div.textContent = toEscape;
result = div.innerHTML;
var map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
result = toEscape.replace(/[&<>"']/g, function(m) { return map[m]; });
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
textContent | |
replace |
Test name | Executions per second |
---|---|
textContent | 1043360.6 Ops/sec |
replace | 1387305.4 Ops/sec |
Benchmark Overview
The provided JSON represents a JavaScript microbenchmark test case on MeasureThat.net. The benchmark compares the performance of two approaches to escape HTML text: textContent
and replace
. The goal is to determine which approach is faster.
Script Preparation Code
The script preparation code sets up a variable toEscape
with some HTML content, specifically an innerHTML-escaped string containing <div>
elements. This is used as the input for both test cases.
Html Preparation Code
There is no HTML preparation code provided in this benchmark definition.
Test Cases
There are two individual test cases:
textContent
This test case creates a new div
element using document.createElement('div')
, sets its textContent
property to the escaped string, and then assigns the result of div.innerHTML
to the variable result
.
var div = document.createElement('div');
div.textContent = toEscape;
result = div.innerHTML;
Pros:
Cons:
replace
This test case uses the replace()
method with a regular expression to escape the HTML string. The regular expression (/[&<>\"']/g)
matches any of the characters &
, <
, >
, "
, or '
in a global manner (g
). The callback function returns the escaped character using an object map.
var map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
result = toEscape.replace(/[&<>\"']/g, function(m) { return map[m]; });
Pros:
textContent
since it avoids creating a new element.Cons:
Library Usage (None)
There are no libraries used in this benchmark definition.
Special JS Features/Syntax (None)
There are no special JavaScript features or syntaxes used in this benchmark definition.
Alternative Approaches
Other alternatives for escaping HTML text include:
html()
method, which automatically escapes special characters.These approaches may have different trade-offs in terms of performance, complexity, and maintainability. The choice of approach depends on the specific use case and requirements.