Which is quicker in JavaScript: appending a string or an array?

Which one is quicker?

let str = '';
for(let i=0; i<1000; i++) {
    str += i;
}

or

let arr = [];
for(let i=0; i<1000; i++) {
    arr.push(i);
}
let str = arr.join(''); 

I am curious about the speed difference between these two methods. I have developed a CSS parser that performs well, but struggles with larger stylesheets due to its speed. I am exploring ways to optimize it, and I am wondering if this would make any impact. Thank you in advance!

Answer №1

In a comparison between string concatenation and array join for speed (this thread provides insight), it is evident that string concatenation is faster, as demonstrated in the following test:

function concatStrings() {
  var str = '';
  for (var i = 0; i < 1000; i++) {
    str += i;
  }
}

function joinArray() {
  var arr = [];
  for (var i = 0; i < 1000; i++) {
    arr.push(i);
  }
  var str = arr.join('');
}


var startTime = new Date();
for (var counter = 0; counter < 10000; counter++) {
  concatStrings()
}
var endTime = new Date();
alert("String Concatenation Time: " + (endTime - startTime));


var startTime = new Date();
for (var counter = 0; counter < 10000; counter++) {
  joinArray()
}
var endTime = new Date();
alert("Array Join Time: " + (endTime - startTime));

The results show that string concatenation takes only one-third of the time compared to Array join.

Answer №2

console.time('b')
var total = '';
for(var x=0; x<10000; x++) {
    total += x;
}
console.timeEnd('b')

VM607:6 b: 1.870ms

console.time('b')
var numbers = [];
for(var y=0; y<10000; y++) {
    numbers.push(y);
}
var result = numbers.join('');
console.timeEnd('b')

VM618:7 b: 2.629ms

Answer №3

After conducting some performance tests, it became evident that the length of the string plays a crucial role, particularly when using the Array.prototype.join() method. It is advisable to avoid unnecessary string concatenation for better results.

String Concatenation:

var t = 0,
    p = 0,
    s = "",
    i = 0;
while (t<=1000) {
p = performance.now();
s +=i;
t += performance.now()-p;
i++;
}
document.write("<pre> Completed " + i + " string concat operations per second</pre>");

Using Array.push() and Array.join():

var t = 0,
p = 0,
a = [],
s = "",
i = 0;
while (t<=1000) {
p = performance.now();
a.push(i)
s = a.join("")
t += performance.now()-p;
i++;
}
document.write("<pre> Completed " + i + " Array.push() + Array.join() operations per second</pre>");

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

storing audio files locally with Vue.js

Looking for a way to store a sound locally for my Battleship game rather than referencing it on the internet. Here's the code that triggers the sound: @click.prevent="fireSound('http://soundbible.com/grab.php?id=1794&type=mp3')" I atte ...

When using react-hook-form within a .map() function, it encounters an issue causing it to fail - specifically, a TypeError message stating "Cannot read properties of undefined (reading '

Confused and frustrated here, I can't seem to get this form working properly. I have a Checkbox component that works fine when not in a loop, but as soon as I try to integrate it into a loop, everything breaks. Checkbox.tsx const Checkbox = React.for ...

How can I resolve the ReferenceError in NextJs which states that Audio is not defined?

Recently, I implemented a Next component that acts as a music player, allowing users to play or stop the audio just like an MP3 player. While the functionality works perfectly fine on my local server – clicking the button triggers the audio play or pause ...

What is the process for arranging multiple text boxes beside a radio button upon selection?

Displayed below is the HTML code for a page featuring three radio buttons- <html> <body> <form> <input type="radio" name="tt1" value="Insert" /> Insert<br /> <input type="radio" name="tt2" value="Update" /> Update<b ...

The PHP query that was sent through an AJAX POST request is not being executed correctly

I have a situation where I am working with two pages: Page 1: <input type="hidden" name="rateableUserID" value="<?php echo $rateableUserID;?>"/> <input type="hidden" name="rateablePictureID" value="<?php echo $rateablePictureID;?>"/& ...

The JSON file now contains the name of the variable rather than its value

When receiving a json from an API I created, it contains various values and one of them needs to be appended to another json object. Here is the original json where the data should be added: originalOrder = { "name": 1, "su ...

Vertical sorting of arrays in JavaScript based on index positions

Here is an array containing the letters of the alphabet: ["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"] From the server, I receive the number of columns to display. Let's assume it's 3 f ...

Tips for importing in VScode without including an index at the end of the URL

I'm attempting to set up vs-code so it can identify and propose imports without the need for an index file. foo (folder) - index (js file) current behavior: import './foo/index' expected behavior: import './foo' I've tri ...

Express server controller encountering premature return from locally executed async function

I have developed an API endpoint using Node/Express. I am trying to call a local function asynchronously within the controller function, but instead of receiving the expected asynchronous results, the called local function is returning undefined immediat ...

Creating a Mithril.js Single Page Application (SPA) using a JSON data source: A

I am currently working on creating a single page application (SPA) using Mithril.js. While I have come across some helpful tutorials like the one here and on the official Mithril homepage, I am struggling to combine the concepts from both sources effective ...

Enhancing ajax content with Rx.Observable.fromEvent: A step-by-step guide

I am currently fetching content using Ajax, in the form of a json object, which is then displayed in the browser. var stateSubjectSub = stateSubject.subscribe(function(data) { console.log('state changes'); console.log(data); var list = document ...

Guide on spinning a particle in three.js

I am encountering an issue with a particle that leaves a circle behind when rotated as an image. How can I eliminate this unwanted circle effect? Check out the code on this Fiddle: http://jsfiddle.net/zUvsp/137/ Here's the code snippet: var camera, ...

Running `npm install npm` results in encountering gyp ERR and npm ERR

Why am I encountering this peculiar error message when executing sudo npm install npm? This issue seems to crop up occasionally with other modules as well! Error: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d4a7b7a6ad ...

Challenges related to pointers within an array of structures

Having a C problem with a microcontroller. My struct has values for the 'Node' hardware instance, each tied to a 'register'. A 'register' contains read/write details, status flags, and a pointer to the Node struct value. An ...

Guide to custom sorting and sub-sorting in AngularJS

If I have an array of objects like this: [ { name: 'test1', status: 'pending', date: 'Jan 17 2017 21:00:23' }, { name: 'test2', sta ...

Troubleshooting a scenario where making edits to a mongoDB item does not result in any updates

I am struggling with a problem in my nodeJS application involving updating items in a mongoDB database. I have successfully implemented features to add and remove notes, but when attempting to update a note, the changes do not reflect in the database. Desp ...

Ways to incorporate radio buttons, checkboxes, and select fields into a multi-step form using JavaScript

In the snippet below, I have created a multi-step form where users can provide details. The issue is that currently only text input fields are being accepted. The array of questions specifies the type of input required for each question: Question no.1 req ...

Ways to extract text content excluding HTML elements

Managing a database table for news storage has been pretty straightforward, as the field type is TEXT which allows me to save the news with inline styles. However, I encountered an issue when trying to display the last 10 news items on the main page. While ...

Angular 6 - Preload service with asynchronous requests prior to injecting dependencies

I've encountered an issue with my service that loads a configuration object in memory based on the environment file. The problem is that the settings are read asynchronously, causing the application to start before all settings are loaded and resultin ...

I have successfully integrated my custom external JavaScript code with React Router, and everything is working

Assistance Needed! I am working on a project that consists of 4 pages, one of which is the About page. I am using react-router to manage the paths and contents between these pages through their respective links. import React from 'react'; impo ...