JavaScript 有内置的 stringbuilder 类吗?

发布于 2024-08-17 21:15:11 字数 149 浏览 5 评论 0原文

我看到一些代码项目解决方案

但是JavaScript中有常规的实现吗?

I see a few The Code Project solutions.

But is there a regular implementation in JavaScript?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

绝影如岚 2024-08-24 21:15:11

如果您必须为 Internet Explorer 编写代码,请确保您选择了使用数组连接的实现。在 IE 上,使用 ++= 运算符连接字符串的速度非常慢。对于 IE6 来说尤其如此。在现代浏览器上 += 通常与数组连接一样快。

当我必须进行大量字符串连接时,我通常会填充一个数组并且不使用字符串生成器类:

var html = [];
html.push(
  "<html>",
  "<body>",
  "bla bla bla",
  "</body>",
  "</html>"
);
return html.join("");

请注意,push 方法接受多个参数。

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.

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 push methods accepts multiple arguments.

小兔几 2024-08-24 21:15:11

我刚刚重新检查了 http://jsperf.com/javascript-concat-vs- 的性能加入/2
测试用例连接或连接字母表 1,000 次。

在当前的浏览器(Firefox、Opera、Internet Explorer 11 和 Chrome)中,“concat”比“join”快约 4-10 倍。

Internet Explorer 8 中,两者返回的结果大致相同。

不幸的是,在 Internet Explorer 7 中,“加入”速度大约快了 100 倍。

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.

In current browsers (Firefox, Opera, Internet Explorer 11, and Chrome), "concat" is about 4-10 times faster than "join".

In Internet Explorer 8, both return about equal results.

In Internet Explorer 7, "join" is about 100 times faster unfortunately.

听不够的曲调 2024-08-24 21:15:11

不,没有构建字符串的内置支持。您必须改用串联。

当然,您可以创建一个由字符串的不同部分组成的数组,然后对该数组调用 join(),但这取决于您使用的 JavaScript 解释器中如何实现连接。

我做了一个实验来比较 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));

我在 Windows 7 x64 上的 Internet Explorer 8 和 Firefox 3.5.5 中对其进行了测试。

一开始,我测试了少量迭代(数百、数千项)。结果是不可预测的(有时字符串连接需要 0 毫秒,有时需要 16 毫秒,数组连接也是如此)。

当我将计数增加到 50,000 时,不同浏览器中的结果有所不同 - 在 Internet Explorer 中,字符串连接速度更快(94 毫秒),而连接速度更慢(125 毫秒),而在 Firefox 中,数组连接速度更快(113 毫秒)比字符串连接(117 毫秒)。

然后我将计数增加到 500'000。现在,在两种浏览器中,array.join()比字符串连接慢:Internet Explorer 中的字符串连接为 937 毫秒,Firefox 中为 1155 毫秒,Internet 中的数组连接为 1265 毫秒;Explorer,Firefox 中为 1207 毫秒。

我可以在 Internet Explorer 中测试而不会出现“脚本执行时间过长”的最大迭代次数为 850,000。然后 Internet Explorer 的字符串连接为 1593,数组连接为 2046,而 Firefox 的字符串连接为 2101,数组连接为 2249。

结果 - 如果迭代次数较少,您可以尝试使用 array.join(),因为它在 Firefox 中可能会更快。当数量增加时,string1+string2 方法速度更快。

更新

我在 Internet Explorer 6 (Windows XP) 上执行了测试。如果我尝试进行超过 100,000 次迭代的测试,该过程会立即停止响应并且永远不会结束。
在 40,000 次迭代中,结果为

Time (strings): 59175 ms
Time (arrays): 220 ms

这意味着 - 如果您需要支持 Internet Explorer 6,请选择 array.join(),这比字符串连接快得多。

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.

I made an experiment to compare the speed of str1+str2 method versus array.push(str1, str2).join() method. The code was simple:

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.

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).

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).

Then I increased the count to 500'000. Now the array.join() was slower than string concatenation in 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.

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.

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+string2 method is faster.

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

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.

早乙女 2024-08-24 21:15:11

该代码看起来像是您想要采取的路线,但需要进行一些更改。

您需要将追加方法更改为如下所示。我已将其更改为接受数字 0,并使其返回 this,以便您可以链接您的追加。

StringBuilder.prototype.append = function (value) {
    if (value || value === 0) {
        this.strings.push(value);
    }
    return this;
}

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 this so you can chain your appends.

StringBuilder.prototype.append = function (value) {
    if (value || value === 0) {
        this.strings.push(value);
    }
    return this;
}
韶华倾负 2024-08-24 21:15:11

JavaScript 的 StringBuilder 试试这个..

  
function StringBuilder(value) {
    this.strings = new Array();
    this.append(value);
}

StringBuilder.prototype.append = function (value) {
    if (value) {
        this.strings.push(value);
    }
}

StringBuilder.prototype.clear = function () {
    this.strings.length = 0;
}

StringBuilder.prototype.toString = function () {
    return this.strings.join("");
}

var sb = new StringBuilder();
sb.append("This is");
sb.append("much better looking");
sb.append("than using +=");

var myString = sb.toString();

sb.clear();

StringBuilder for JavaScript try this..

  
function StringBuilder(value) {
    this.strings = new Array();
    this.append(value);
}

StringBuilder.prototype.append = function (value) {
    if (value) {
        this.strings.push(value);
    }
}

StringBuilder.prototype.clear = function () {
    this.strings.length = 0;
}

StringBuilder.prototype.toString = function () {
    return this.strings.join("");
}

var sb = new StringBuilder();
sb.append("This is");
sb.append("much better looking");
sb.append("than using +=");

var myString = sb.toString();

sb.clear();

贩梦商人 2024-08-24 21:15:11

编辑

不,没有内置类。然而,字符串文字可能是一个合适的解决方法。

原始答案

JavaScript 的 ECMAScript 6 版本(又名 ECMAScript 2015)引入了 字符串文字

var classType = "stringbuilder";
var q = `Does JavaScript have a built-in ${classType} class?`;

请注意,用反引号而不是单引号将字符串括起来。

EDIT

No, there is not a built-in class. However, string literals may be a suitable work-around.

ORIGINAL ANSWER

The ECMAScript 6 version (aka ECMAScript 2015) of JavaScript introduced string literals.

var classType = "stringbuilder";
var q = `Does JavaScript have a built-in ${classType} class?`;

Notice that back-ticks, instead of single quotes, enclose the string.

浮生面具三千个 2024-08-24 21:15:11

下面是 TypeScript 中 StringBuilder 类的一个简单示例:

export class StringBuilder {
  private _lines: string[] = [];

  write(line: string = ""): void {
    this._lines.push(line);
  }

  writeln(line: string = ""): void {
    this._lines.push(line);
    this._lines.push("\n");
  }

  toString(): string {
    return this._lines.join("");
  }
}

您可以像下面这样使用:

const sb = new StringBuilder();
sb.write("Hello World");
sb.writeln("!");
console.log(sb.toString());

Here is a quick example of a StringBuilder class in TypeScript:

export class StringBuilder {
  private _lines: string[] = [];

  write(line: string = ""): void {
    this._lines.push(line);
  }

  writeln(line: string = ""): void {
    this._lines.push(line);
    this._lines.push("\n");
  }

  toString(): string {
    return this._lines.join("");
  }
}

You can use like the following:

const sb = new StringBuilder();
sb.write("Hello World");
sb.writeln("!");
console.log(sb.toString());
雪花飘飘的天空 2024-08-24 21:15:11

对于那些感兴趣的人,这里有一个调用 Array.join 的替代方法:

var arrayOfStrings = ['foo', 'bar'];
var result = String.concat.apply(null, arrayOfStrings);
console.log(result);

正如预期的那样,输出是字符串“foobar”。在 Firefox 中,此方法优于 Array.join,但优于 + 连接。由于 String.concat 要求将每个段指定为单独的参数,因此调用者受到执行 JavaScript 引擎施加的任何参数计数限制的限制。查看文档Function.prototype.apply() 了解更多信息。

For those interested, here's an alternative to invoking 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.

从来不烧饼 2024-08-24 21:15:11

当我发现自己在 JavaScript 中进行了大量字符串连接时,我开始寻找模板。 Handlebars.js 工作得很好,使 HTML 和 JavaScript 更具可读性。 http://handlebarsjs.com

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

中性美 2024-08-24 21:15:11

在 C# 中你可以做类似的事情

 String.Format("hello {0}, your age is {1}.",  "John",  29) 

在 JavaScript 中你可以做类似的事情

 var x = "hello {0}, your age is {1}";
 x = x.replace(/\{0\}/g, "John");
 x = x.replace(/\{1\}/g, 29);

In C# you can do something like

 String.Format("hello {0}, your age is {1}.",  "John",  29) 

In JavaScript you could do something like

 var x = "hello {0}, your age is {1}";
 x = x.replace(/\{0\}/g, "John");
 x = x.replace(/\{1\}/g, 29);
明月夜 2024-08-24 21:15:11

使用sys.StringBuilder()。尝试一下文章Sys.StringBuilder Class

Use sys.StringBuilder(). Try the article Sys.StringBuilder Class.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文