Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Time Complexity for string concatenation in JavaScript

I am learning algorithms. And I didn't find any articles about how to calculate Time Complexity of string concatenation in JavaScript.

function concatString(str1, str2) {
  // return str1 + str2;
  // return str1.concat(str2)
}

We can concat strings using operator '+' or using built-in method String.prototype.concat

Which method is better? What is the Time Complexity of both methods?

like image 970
Yevheniy Holubiev Avatar asked Nov 14 '25 17:11

Yevheniy Holubiev


1 Answers

According to the documentation, the difference between using + and concat() is that contat() will convert the argument directly to a string while the + operator will convert the operands to a primitive value and then into a string. Summarizing, it will not make a significant difference.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/concat#description


The time complexity of concat operations in another language like Java is usually O(n^2), and is a common practice to use a StringBuilder to make it O(n). In JavaScript though, there is an optimized implementation of concatenation based on the rope data structure, making the time complexity O(log n) in most cases.

https://josephmate.github.io/java/javascript/stringbuilder/2020/07/27/javascript-does-not-need-stringbuilder.html

like image 81
Artur Luis Avatar answered Nov 17 '25 16:11

Artur Luis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!