gpt4 book ai didi

javascript - 什么是 replaceAll 性能 secret ? [HTML 转义]

转载 作者:可可西里 更新时间:2023-11-01 02:44:52 24 4
gpt4 key购买 nike

我花了一些时间寻找转义 html 字符串的最佳方法,并找到了一些相关讨论:discussion 1 discussion 2 .它引导我到 replaceAll功能。然后我做了性能测试并试图找到实现类似速度但没有成功的解决方案:(

这是我的决赛 test case set .我在网上找到它并尝试扩展(底部有 4 个案例),但仍然无法达到 replaceAll() 性能。

是什么 secret 使 replaceAll() 解决方案如此快速?

您好!

代码片段:

String.prototype.replaceAll = function(str1, str2, ignore) 
{
return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g,"\\$&"),(ignore?"gi":"g")),(typeof(str2)=="string")?str2.replace(/\$/g,"$$$$"):str2);
};

qwerty 的学分

目前最快的案例:

html.replaceAll('&', '&amp;').replaceAll('"', '&quot;').replaceAll("'", '&#39;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');

最佳答案

终于找到了!谢谢Jack为我指出 jsperf 的具体内容

I should note that the test results are strange; when .replaceAll() is defined inside Benchmark.prototype.setup it runs twice as fast compared to when it's defined globally (i.e. inside a tag). I'm still not sure why that is, but it definitely must be related to how jsperf itself works.

答案是:

replaceAll - 这达到了 jsperf 限制/错误,由特殊序列 "\\$&" 引起,所以结果是错误的。

compile() - 当不带参数调用时,它会将正则表达式定义更改为 /(?:)。不知道是bug还是什么,调用后性能很差。

这是我的 result safe tests .

终于准备好了proper test cases .

结果是,对于 HTML 转义,最好的方法是使用基于本地 DOM 的解决方案,例如:

document.createElement('div').appendChild(document.createTextNode(html)).parentNode.innerHTML

或者如果你重复多次,你可以用一次准备好的变量来做:

//prepare variables
var DOMtext = document.createTextNode("test");
var DOMnative = document.createElement("span");
DOMnative.appendChild(DOMtext);

//main work for each case
function HTMLescape(html){
DOMtext.nodeValue = html;
return DOMnative.innerHTML
}

感谢大家的合作以及发表评论和指导。

jsperf 错误描述

String.prototype.replaceAll 定义如下:

function (str1, str2, ignore) {
return this.replace(new RegExp(str1.replace(repAll, "\\#{setup}"), (ignore ? "gi" : "g")), (typeof(str2) == "string") ? str2.replace(/\$/g, "$$") : str2);
}

关于javascript - 什么是 replaceAll 性能 secret ? [HTML 转义],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17442098/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com