DEV Community

Cover image for Favorite String Literals
Kristen Kinnear-Ohlmann
Kristen Kinnear-Ohlmann

Posted on • Originally published at kristenkinnearohlmann.dev

Favorite String Literals

I was recently listening to a JavaScript tutorial on 2x speed when I caught something that caused me to slow down and rewind. The presenter was talking about strings, concatenation, and ES6 string literals. The statement that caught my attention I summarized as "Go ahead and start with template literals first so you don't need to change to backticks later when you need to use a variable".

JavaScript

// instead of concatenation
// start with a template literal
let numberOfCats = 5;
console.log(`I have ${numberOfCats} cats.`);
console.log(`Now I have ${numberOfCats+1} cats.`);
Enter fullscreen mode Exit fullscreen mode

This struck me as very sensible! There are many advantages to using a string literal instead of a basic statement or simple concatenation and you would save yourself time in refactoring code if you were already using them. They are more readable than other ways of formatting strings; they look like normal sentences and allow you to more easily identify portions to change or update.

I realized I could apply this kind of strategy to some of the other languages I know as well:

Python

# instead of concatenation
# use an 'f' string in Python 3 right away
number_of_cats = 5
f"I have {number_of_cats} cats"
Enter fullscreen mode Exit fullscreen mode

C#

// instead of String.Format() (ex. Console.WriteLine("Hello {0}", "world"))
// use string interpolation
string numberOfCats = 5;
Console.WriteLine($"I have {numberOfCats} cats.");
Enter fullscreen mode Exit fullscreen mode

By using these techniques right away in your code, you save time and effort and increase the accuracy of your code when changes occur.

Further Reading

Top comments (13)

Collapse
 
pyrsmk profile image
Aurélien Delogu • Edited

Ruby/Crystal has also string interpolation which is so handy!

"Hello, I'm #{age}" 
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

One thing that is rarely mentioned is that template literals are pretty much consistently slower than using string literals in JS. So, if you're doing heavy string processing at volume, you're probably better off avoiding template strings.

Collapse
 
mrcaidev profile image
Yuwang Cai

Nice tool! But I played with it a few times, and the test results actually shows that the performance of the two solutions are almost the same, either for string concatenation or just plain text. In the above two cases, template literals even wins.
I do used to think template literals are slower (it just makes sense, right?), until I came across this blog a few days ago. There are really not so much performance loss, but as the author says, we "don't need to change to backticks later when you need to use a variable", and backticks are great with no need to escape ' or " and allows multi-line strings. So now I would opt for backticks more, unless there are some convincing reasons I shouldn't do so. 😄

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Interesting - it's almost always 20-30% slower for me, on both Chrome and Firefox

Thread Thread
 
mrcaidev profile image
Yuwang Cai

Results vary for every one every time 😂 Maybe it's subject to environment or context changes - I don't know. And that's why I don't consider performance as a serious main issue, and the difference of those nanoseconds can almost be ignored in actual projects. 😃

Collapse
 
pyrsmk profile image
Aurélien Delogu

But most of the time this is just micro optimization.

Collapse
 
fjones profile image
FJones

I have to disagree. Use the most-restrictive string literal whereever possible. Don't need apostrophes? Use '. Don' t need interpolation (in JS)? Use ".

Though, to be fair, I've reneged a bit on that and am now enforcing "" unless template literals are needed" in our linter rules.

Collapse
 
leob profile image
leob

PHP also has them :)

Collapse
 
pyrsmk profile image
Aurélien Delogu

Not really. It just has "anything that begins with a $ sign" interpolation. Which is quite annoying IMO 😅

Collapse
 
fjones profile image
FJones

Fair, but PHP does still (unless I missed something) distinguish between interpolated (" and <<<END") strings and non-interpolated ones.

Thread Thread
 
pyrsmk profile image
Aurélien Delogu

Indeed. Single quoted strings cannot be interpolated.

Thread Thread
 
fjones profile image
FJones

Neither can NOWDOC (<<<'END'), which is quite important at times. HEREDOC (<<<END) does get interpolated.

There's few reasons to choose interpolation in PHP, but the ones I've found over the years tend to actually be HEREDOC rather than regular string literals (code generation with HEREDOC is lovely!).

Thread Thread
 
pyrsmk profile image
Aurélien Delogu

I admit that I rarely used them.