MDN has the following to say about string.concat():
It is strongly recommended to use the string concatenation operators (+, +=) instead of this method for perfomance reasons
Also see the link by @Bergi.
Answer from laktak on Stack OverflowMDN has the following to say about string.concat():
It is strongly recommended to use the string concatenation operators (+, +=) instead of this method for perfomance reasons
Also see the link by @Bergi.
In JS, "+" concatenation works by creating a new String object.
For example, with...
var s = "Hello";
...we have one object s.
Next:
s = s + " World";
Now, s is a new object.
2nd method: String.prototype.concat
Videos
Consider this piece of JavaScript code:
var a = 10;
var b = 20;
console.log('result is ' + a + b);
This will log
result is 1020
Which most likely is not what was intended, and can be a hard to track bug.
When you say "bad" do you mean "incorrect" or do you mean "slow"? The argument about using mathematical operators to do string concatenation is arguably an "incorrect" argument, but there's also an argument to be made that using + to do a lot of string concatenation can be very slow.
We're not talking about "Hello" + number when we talk about performance, we're talking about building up a relatively large string by repeatedly appending to it in a loop.
var combined = "";
for (var i = 0; i < 1000000; i++) {
combined = combined + "hello ";
}
In JavaScript (and C# for that matter) strings are immutable. They can never be changed, only replaced with other strings. You're probably aware that combined + "hello " doesn't directly modify the combined variable - the operation creates a new string that is the result of concatenating the two strings together, but you must then assign that new string to the combined variable if you want it to be changed.
So what this loop is doing is creating a million different string objects, and throwing away 999,999 of them. Creating that many strings that are continually growing in size is not fast, and now the garbage collector has a lot of work to do to clean up after this.
C# has the exact same problem, which is solved in that environment by the StringBuilder class. In JavaScript, you'll get much better performance by building up an array of all the strings you want to concatenate, and then joining them together one time at the end, instead of a million times in the loop:
var parts = [];
for (var i = 0; i < 1000000; i++) {
parts.push("hello");
}
var combined = parts.join(" ");
I have a server that uses the chat gpt api with stream (SSE) and I have to concatenate all the chucks it sends.
I wanted to know if there is something more efficient than +=, in other languages they recommend using a String Buffer, in js/ts I don't know what is best.
Thank you so much.
async function main() {
const stream = await openai.chat.completions.create({
model: 'gpt-4',
messages: [{ role: 'user', content: 'Say this is a test' }],
stream: true,
});
for await (const part of stream) {
process.stdout.write(part.choices[0]?.delta?.content || '');
}
}I've been working on a project at work and one of the guys that was there before me and supposedly a senior web developer created a whole application with dynamically generated HTML code which looks something like this:
var name = 'Bob';
var text = [];
text.push('Hello ');
text.push(name);
text.push(" how's your day going?");
text.push('My day is going fine thanks ');
text.push(name);
text = text.join('');Which completely baffled me. I would've thought it was cleaner and more readable to simply do:
var text = ''; var name = 'Bob'; text += 'Hello ' + name + " how's your day going?"; text += 'My day is going fine thanks ' + name;
Is there any reason for using the join() or concatenating the strings like that? I created a jsFiddle and it appears using the array and join() method is 3 times slower.
I'm learning Javascript through Udemy at the moment and they have just explained that you can inject variables into string using ${example} instead of concatenating.
What is the benefit to injecting variables this way instead of concatenating?
Hi, I'm new-ish to web dev, by way of web design, by way of graphic design, so I have a lot to learn. I think maybe I'm missing something re template literals. consider:
return '<h1>Hello ' + firstName + ', welcome to your account.</h1>';
and
return `<h1>Hello '${ firstName }', welcome to your account.</h1>`;Ok, so you're typing 1 less char, is that the only benefit? Are there performance benefits? It's certainly not significantly more legible or anything. What's the use case where template literals are just far and away superior to plain old string concat?
EDIT: Thanks everyone, I feel like I know when and how to use template literals now.