数组连接与字符串连接

发布于 2024-12-03 02:57:47 字数 493 浏览 0 评论 0原文

哪种方法更快?

数组连接:

var str_to_split = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
var myarray = str_to_split.split(",");

var output=myarray.join("");

字符串连接:

var str_to_split = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
var myarray = str_to_split.split(",");

var output = "";
for (var i = 0, len = myarray.length; i<len; i++){
    output += myarray[i];
}

Which method is faster?

Array Join:

var str_to_split = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
var myarray = str_to_split.split(",");

var output=myarray.join("");

String Concat:

var str_to_split = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
var myarray = str_to_split.split(",");

var output = "";
for (var i = 0, len = myarray.length; i<len; i++){
    output += myarray[i];
}

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

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

发布评论

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

评论(10

悲欢浪云 2024-12-10 02:57:47

ECMAScript 中的字符串连接速度更快。这是我为向您展示而创建的基准:

http://jsben.ch/#/OJ3vo

String concatenation is faster in ECMAScript. Here's a benchmark I created to show you:

http://jsben.ch/#/OJ3vo

嘦怹 2024-12-10 02:57:47

从 2011 年到现代...

请参阅以下使用字符串连接的 join 重写,以及它比标准实现慢了多少。

// Number of times the standard `join` is faster, by Node.js versions:
// 0.10.44: ~2.0
// 0.11.16: ~4.6
// 0.12.13: ~4.7
// 4.4.4: ~4.66
// 5.11.0: ~4.75
// 6.1.0: Negative ~1.2 (something is wrong with 6.x at the moment)
function join(sep) {
    var res = '';
    if (this.length) {
        res += this[0];
        for (var i = 1; i < this.length; i++) {
            res += sep + this[i];
        }
    }
    return res;
}

道德是 - 不要手动连接字符串,始终使用标准join

From 2011 and into the modern day ...

See the following join rewrite using string concatenation, and how much slower it is than the standard implementation.

// Number of times the standard `join` is faster, by Node.js versions:
// 0.10.44: ~2.0
// 0.11.16: ~4.6
// 0.12.13: ~4.7
// 4.4.4: ~4.66
// 5.11.0: ~4.75
// 6.1.0: Negative ~1.2 (something is wrong with 6.x at the moment)
function join(sep) {
    var res = '';
    if (this.length) {
        res += this[0];
        for (var i = 1; i < this.length; i++) {
            res += sep + this[i];
        }
    }
    return res;
}

The moral is - do not concatenate strings manually, always use the standard join.

撧情箌佬 2024-12-10 02:57:47

我可以肯定地说使用 Array.join() 更快。我编写了几段 JavaScript 代码,并通过删除字符串操作而使用数组来显着提高性能。

I can definitely say that using Array.join() is faster. I've worked on a few pieces of JavaScript code and sped up performance significantly by removing string manipulation in favor of arrays.

救星 2024-12-10 02:57:47

2021 年测试

请参阅下面的代码。结果:

Firefox:在常规使用中,push+join 比字符串连接慢 80%

Chrome:在常规使用中,push+join 比字符串连接慢 140%

function test(items = 100, rep = 1000000) {
  let str

  console.time('concat')
  for (let r = 0; r < rep; r++) {
    str = ''
    for (let i = 0; i < items; i++) {
      str += i
    }
  }
  console.timeEnd('concat')

  console.time('push+join')
  for (let r = 0; r < rep; r++) {
    const arr = []
    for (let i = 0; i < items; i++) {
      arr.push(i)
    }
    str = arr.join('')
  }
  console.timeEnd('push+join')
}

2021 test

See code below. Results:

Firefox: push+join is 80% slower than string concat, in regular usage.

Chrome: push+join is 140% slower than string concat, in regular usage.

function test(items = 100, rep = 1000000) {
  let str

  console.time('concat')
  for (let r = 0; r < rep; r++) {
    str = ''
    for (let i = 0; i < items; i++) {
      str += i
    }
  }
  console.timeEnd('concat')

  console.time('push+join')
  for (let r = 0; r < rep; r++) {
    const arr = []
    for (let i = 0; i < items; i++) {
      arr.push(i)
    }
    str = arr.join('')
  }
  console.timeEnd('push+join')
}
︶ ̄淡然 2024-12-10 02:57:47

当字符串数组已经存在时,join 的速度要快得多。真正的比较是比较:

  1. 将元素推入数组,然后将它们连接起来构建字符串,
  2. 每次都连接字符串,而不使用数组。

对于少量迭代和字符串,使用推送和连接还是连接并不重要。然而,对于大量字符串,数组推送和连接在 Chrome 和 Firefox 中似乎更快

以下是 10 到 1000 万个字符串的代码和测试结果:

Chrome:

strings 10
join-only: 0.01171875 ms
push-join: 0.137939453125 ms
concatenate: 0.01513671875 ms
strings 100
join-only: 0.01416015625 ms
push-join: 0.13427734375 ms
concatenate: 0.0830078125 ms
strings 1000
join-only: 0.048095703125 ms
push-join: 0.47216796875 ms
concatenate: 0.5517578125 ms
strings 10000
join-only: 0.465087890625 ms
push-join: 5.47314453125 ms
concatenate: 4.9619140625 ms
strings 100000
join-only: 7.6240234375 ms
push-join: 57.37109375 ms
concatenate: 67.028076171875 ms
strings 1000000
join-only: 67.666259765625 ms
push-join: 319.3837890625 ms
concatenate: 609.8369140625 ms
strings 10000000
join-only: 824.260009765625 ms
push-join: 3207.129150390625 ms
concatenate: 5959.56689453125 ms

Firefox:

strings 10
join-only: 0ms
push-join: 1ms
concatenate: 0ms
strings 100
join-only: 0ms
push-join: 0ms
concatenate: 0ms
strings 1000
join-only: 0ms
push-join: 1ms
concatenate: 0ms
strings 10000
join-only: 1ms
push-join: 2ms
concatenate: 0ms
strings 100000
join-only: 5ms
push-join: 11ms
concatenate: 8ms
strings 1000000
join-only: 39ms
push-join: 88ms
concatenate: 98ms
strings 10000000
join-only: 612ms
push-join: 1095ms
concatenate: 3249ms

要测试的代码:

for (var n = 10; n <= 10000000; n*=10) {
    
    var iterations = n;

    console.log("strings", iterations);
    console.time("push-join");
    arr = [];
    for (var i = 0; i< iterations; i++) {
        arr.push("a b c d e f g h i j k l m");
    }
    console.time("join-only");
    content = arr.join(",");
    console.timeEnd("join-only");
    console.timeEnd("push-join");

    content = "";

    console.time("concatenate");    
    for (var i = 0; i< iterations; i++) {
        content += "a b c d e f g h i j k l m";
    }
    console.timeEnd("concatenate");

}

join is way faster when the array of strings already exists. The real comparison would be comparing:

  1. push elements into the array and then join them to build the string
  2. concatenate string every time without using the array

For small number of iteration and strings, it does not matter whether you use push-and-join or concatenate. However, for large number of strings, array push and join seems to be faster in both chrome and firefox.

Here is the code and the test results for 10 to 10 million strings:

Chrome:

strings 10
join-only: 0.01171875 ms
push-join: 0.137939453125 ms
concatenate: 0.01513671875 ms
strings 100
join-only: 0.01416015625 ms
push-join: 0.13427734375 ms
concatenate: 0.0830078125 ms
strings 1000
join-only: 0.048095703125 ms
push-join: 0.47216796875 ms
concatenate: 0.5517578125 ms
strings 10000
join-only: 0.465087890625 ms
push-join: 5.47314453125 ms
concatenate: 4.9619140625 ms
strings 100000
join-only: 7.6240234375 ms
push-join: 57.37109375 ms
concatenate: 67.028076171875 ms
strings 1000000
join-only: 67.666259765625 ms
push-join: 319.3837890625 ms
concatenate: 609.8369140625 ms
strings 10000000
join-only: 824.260009765625 ms
push-join: 3207.129150390625 ms
concatenate: 5959.56689453125 ms

Firefox:

strings 10
join-only: 0ms
push-join: 1ms
concatenate: 0ms
strings 100
join-only: 0ms
push-join: 0ms
concatenate: 0ms
strings 1000
join-only: 0ms
push-join: 1ms
concatenate: 0ms
strings 10000
join-only: 1ms
push-join: 2ms
concatenate: 0ms
strings 100000
join-only: 5ms
push-join: 11ms
concatenate: 8ms
strings 1000000
join-only: 39ms
push-join: 88ms
concatenate: 98ms
strings 10000000
join-only: 612ms
push-join: 1095ms
concatenate: 3249ms

Code to test:

for (var n = 10; n <= 10000000; n*=10) {
    
    var iterations = n;

    console.log("strings", iterations);
    console.time("push-join");
    arr = [];
    for (var i = 0; i< iterations; i++) {
        arr.push("a b c d e f g h i j k l m");
    }
    console.time("join-only");
    content = arr.join(",");
    console.timeEnd("join-only");
    console.timeEnd("push-join");

    content = "";

    console.time("concatenate");    
    for (var i = 0; i< iterations; i++) {
        content += "a b c d e f g h i j k l m";
    }
    console.timeEnd("concatenate");

}
惟欲睡 2024-12-10 02:57:47

这取决于:

铬 79.0.3945

数组连接速度慢 30%

Firefox 71.0.0

字符串连接速度慢 90%

https://jsperf.com/lin-array-连接与字符串连接

It depends:

Chromium 79.0.3945

Array Join is 30% slower

Firefox 71.0.0

String Concat is 90% slower

https://jsperf.com/lin-array-join-vs-string-concat

绝情姑娘 2024-12-10 02:57:47

根据这份标题为的 Google 文档优化 JavaScript 代码的字符串连接比数组连接慢,但显然对于现代 Javascript 引擎来说并非如此。

我为他们在文档中使用的斐波那契测试示例制作了基准,它显示了连接(粘合)字符串的速度几乎是使用 Array join 的 4 倍。

According to this Google document titled 'Optimizing JavaScript code' string concat is slower then array join but apparently this is not true for modern Javascript engines.

I made a benchmark for the Fibonacci test example that they used in the document and it shows that concatenating (gluing) the string is almost 4x as fast as using Array join.

树深时见影 2024-12-10 02:57:47

对于固定长度的数值数组,手动连接速度更快。

这是一个测试这两个操作的 JSPerf 测试

zxy.join('/')

// versus

zxy[0] + '/' + zxy[1] + '/' + zxy[2]

// given the array

zxy = [1, 2, 3]

// resulting in the string '0/1/2'

结果:使用 Chrome 64.0.3282.186,Array.join 速度慢了 46%。

Manual concatenation is faster, for a numeric array of fixed length.

Here's a JSPerf test that tests these two operations:

zxy.join('/')

// versus

zxy[0] + '/' + zxy[1] + '/' + zxy[2]

// given the array

zxy = [1, 2, 3]

// resulting in the string '0/1/2'

Results: Using Chrome 64.0.3282.186, Array.join was 46% slower.

时光磨忆 2024-12-10 02:57:47

我认为这不仅是性能问题,而且是内存问题

,因为字符串是不可变的,这意味着每次连接字符串时,都会在内存中创建一个额外的字符串,

但数组是可变的,这意味着它将保持相同的内存地址,

当然它也是取决于语言,一般来说,数组是更好的解决方案

i think it is not only performance problem, but memory too

as string is immutable, means every time you concat a string, a extra string create in your memory

but array is mutable, mean it will keep the same memory address

of course it is also depend on languages, in general , array is a better solution

热鲨 2024-12-10 02:57:47

扩展运算符由三个连续的点 ( ... ) 编写,是 ES6 中的新增功能,它使您能够将可迭代对象扩展或扩展为多个元素。

const books = ["Don Quixote", "The Hobbit", "Alice in Wonderland", "Tale of Two Cities"];
console.log(...books);

版画: 唐吉诃德 霍比特人 爱丽丝梦游仙境 两座城市的故事

The spread operator, written with three consecutive dots ( ... ), is new in ES6 and gives you the ability to expand, or spread, iterable objects into multiple elements.

const books = ["Don Quixote", "The Hobbit", "Alice in Wonderland", "Tale of Two Cities"];
console.log(...books);

Prints: Don Quixote The Hobbit Alice in Wonderland Tale of Two Cities

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