JavaScript 有内置的 stringbuilder 类吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2087522/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Does JavaScript have a built in stringbuilder class?
提问by leora
I see a few code project solutions.
我看到了一些代码项目解决方案。
But is there a regular implementation in JavaScript?
但是 JavaScript 中是否有常规实现?
回答by Fabian Jakobs
If you have to write code for Internet Explorer make sure you chose an implementation, which uses array joins. Concatenating strings with the +or +=operator are extremely slow on IE. This is especially true for IE6. On modern browsers +=is usually just as fast as array joins.
如果您必须为 Internet Explorer 编写代码,请确保您选择了一个使用数组连接的实现。在 IE 上使用+or+=运算符连接字符串非常慢。对于 IE6 尤其如此。在现代浏览器+=上,通常与数组连接一样快。
When I have to do lots of string concatenations I usually fill an array and don't use a string builder class:
当我必须进行大量字符串连接时,我通常会填充一个数组并且不使用字符串构建器类:
var html = [];
html.push(
"<html>",
"<body>",
"bla bla bla",
"</body>",
"</html>"
);
return html.join("");
Note that the pushmethods accepts multiple arguments.
请注意,这些push方法接受多个参数。
回答by Andreas
I just rechecked the performance on http://jsperf.com/javascript-concat-vs-join/2. The test-cases concatenate or join the alphabet 1,000 times.
我刚刚重新检查了http://jsperf.com/javascript-concat-vs-join/2上的性能。测试用例连接或加入字母表 1,000 次。
In current browsers (FF, Opera, IE11, Chrome), "concat" is about 4-10 times faster than "join".
在当前的浏览器(FF、Opera、IE11、Chrome)中,“concat”大约比“join”快 4-10 倍。
In IE8, both return about equal results.
在 IE8 中,两者都返回大致相同的结果。
In IE7, "join" is about 100 times faster unfortunately.
不幸的是,在 IE7 中,“加入”大约快 100 倍。
回答by naivists
No, there is no built-in support for building strings. You have to use concatenation instead.
不,没有对构建字符串的内置支持。您必须改用串联。
You can, of course, make an array of different parts of your string and then call join()on that array, but it then depends on how the join is implemented in the JavaScript interpreter you are using.
当然,您可以创建字符串不同部分的join()数组,然后调用该数组,但这取决于在您使用的 JavaScript 解释器中如何实现连接。
I made an experiment to compare the speed of str1+str2method versus array.push(str1, str2).join()method. The code was simple:
我做了一个实验来比较str1+str2方法与array.push(str1, str2).join()方法的速度。代码很简单:
var iIterations =800000;
var d1 = (new Date()).valueOf();
str1 = "";
for (var i = 0; i<iIterations; i++)
str1 = str1 + Math.random().toString();
var d2 = (new Date()).valueOf();
log("Time (strings): " + (d2-d1));
var d3 = (new Date()).valueOf();
arr1 = [];
for (var i = 0; i<iIterations; i++)
arr1.push(Math.random().toString());
var str2 = arr1.join("");
var d4 = (new Date()).valueOf();
log("Time (arrays): " + (d4-d3));
I tested it in Internet Explorer 8 and Firefox 3.5.5, both on a Windows 7 x64.
我在 Windows 7 x64 上的 Internet Explorer 8 和 Firefox 3.5.5 中对其进行了测试。
In the beginning I tested on small number of iterations (some hundred, some thousand items). The results were unpredictable (sometimes string concatenation took 0 milliseconds, sometimes it took 16 milliseconds, the same for array joining).
一开始我测试了少量的迭代(大约数百个,数千个项目)。结果是不可预测的(有时字符串连接需要 0 毫秒,有时需要 16 毫秒,数组连接也是如此)。
When I increased the count to 50,000, the results were different in different browsers - in Internet Explorer the string concatenation was faster (94 milliseconds) and join was slower(125 milliseconds), while in Firefox the array join was faster (113 milliseconds) than string joining (117 milliseconds).
当我将计数增加到 50,000 时,结果在不同的浏览器中是不同的——在 Internet Explorer 中,字符串连接速度更快(94 毫秒),连接速度更慢(125 毫秒),而在 Firefox 中,数组连接速度(113 毫秒)比字符串连接(117 毫秒)。
Then I increased the count to 500'000. Now the array.join()was slower than string concatenationin both browsers: string concatenation was 937 ms in Internet Explorer, 1155 ms in Firefox, array join 1265 in Internet Explorer, and 1207 ms in Firefox.
然后我将计数增加到 500'000。现在array.join()是慢于字符串连接两个浏览器:字符串连接是在Internet Explorer 937毫秒,1155毫秒在Firefox中,阵列在Internet Explorer中加入1265,并且在Firefox 1207毫秒。
The maximum iteration count I could test in Internet Explorer without having "the script is taking too long to execute" was 850,000. Then Internet Explorer was 1593 for string concatenation and 2046 for array join, and Firefox had 2101 for string concatenation and 2249 for array join.
在没有“脚本执行时间过长”的情况下,我可以在 Internet Explorer 中测试的最大迭代次数是 850,000。然后 Internet Explorer 的字符串连接为 1593,数组连接为 2046,Firefox 的字符串连接为 2101,数组连接为 2249。
Results- if the number of iterations is small, you can try to use array.join(), as it might be faster in Firefox. When the number increases, the string1+string2method is faster.
结果- 如果迭代次数较少,您可以尝试使用array.join(),因为它在 Firefox 中可能会更快。当数量增加时,该string1+string2方法更快。
UPDATE
更新
I performed the test on Internet Explorer 6 (Windows XP). The process stopped to respond immediately and never ended, if I tried the test on more than 100,000 iterations. On 40,000 iterations the results were
我在 Internet Explorer 6 (Windows XP) 上执行了测试。如果我在超过 100,000 次迭代中尝试测试,该过程立即停止响应并且永远不会结束。在 40,000 次迭代中,结果是
Time (strings): 59175 ms
Time (arrays): 220 ms
This means - if you need to support Internet Explorer 6, choose array.join()which is way faster than string concatenation.
这意味着 - 如果您需要支持 Internet Explorer 6,请选择array.join()比字符串连接更快的方式。
回答by Gordon Tucker
That code looks like the route you want to take with a few changes.
该代码看起来像您想要通过一些更改采取的路线。
You'll want to change the append method to look like this. I've changed it to accept the number 0, and to make it return thisso you can chain your appends.
您需要将 append 方法更改为如下所示。我已将其更改为接受数字 0,并使其返回,this以便您可以链接您的附加内容。
StringBuilder.prototype.append = function (value) {
if (value || value === 0) {
this.strings.push(value);
}
return this;
}
回答by Theophilus
The ECMAScript 6 version (aka ECMAScript 2015) of JavaScript introduced string literals.
JavaScript 的 ECMAScript 6 版本(又名 ECMAScript 2015)引入了字符串文字。
var classType = "stringbuilder";
var q = `Does JavaScript have a built-in ${classType} class?`;
Notice that back-ticks, instead of single quotes, enclose the string.
请注意,反引号而不是单引号将字符串括起来。
回答by sports
In C# you can do something like
在 C# 中,你可以做类似的事情
String.Format("hello {0}, your age is {1}.", "John", 29)
In JavaScript you could do something like
在 JavaScript 中,你可以做类似的事情
var x = "hello {0}, your age is {1}";
x = x.replace(/\{0\}/g, "John");
x = x.replace(/\{1\}/g, 29);
回答by TotPeRo
I have defined this function:
我已经定义了这个函数:
function format() {
var args = arguments;
if (args.length <= 1) {
return args;
}
var result = args[0];
for (var i = 1; i < args.length; i++) {
result = result.replace(new RegExp("\{" + (i - 1) + "\}", "g"), args[i]);
}
return result;
}
And can be called like c#:
并且可以像 c# 一样调用:
var text = format("hello {0}, your age is {1}.", "John", 29);
Result:
结果:
hello John, your age is 29.
你好约翰,你的年龄是 29 岁。
回答by Aaron
For those interested, here's an alternative to invoking Array.join:
对于那些感兴趣的人,这是调用 Array.join 的替代方法:
var arrayOfStrings = ['foo', 'bar'];
var result = String.concat.apply(null, arrayOfStrings);
console.log(result);
The output, as expected, is the string 'foobar'. In Firefox, this approach outperforms Array.join but is outperformed by + concatenation. Since String.concat requires each segment to be specified as a separate argument, the caller is limited by any argument count limit imposed by the executing JavaScript engine. Take a look at the documentation of Function.prototype.apply()for more information.
正如预期的那样,输出是字符串“foobar”。在 Firefox 中,这种方法优于 Array.join,但优于 + 连接。由于 String.concat 要求将每个段指定为单独的参数,因此调用方受到执行 JavaScript 引擎施加的任何参数计数限制的限制。查看Function.prototype.apply() 的文档以获取更多信息。
回答by beginning
When I find myself doing a lot of string concatenation in JavaScript, I start looking for templating. Handlebars.js works quite well keeping the HTML and JavaScript more readable. http://handlebarsjs.com
当我发现自己在 JavaScript 中做了很多字符串连接时,我开始寻找模板。Handlebars.js 可以很好地保持 HTML 和 JavaScript 的可读性。http://handlebarsjs.com
回答by Pissu Pusa
How about sys.StringBuilder()try the following article.
sys.StringBuilder()试试下面的文章怎么样。

