Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Big O of javascript built-in split function

Example:

var string = "abcde";
var array = string.split("");
// array = ["a", "b", "c", "d", "e"]

What is the amortized running time of this split function? Also, how do I view source code of such built-in functions in javascript?

like image 554
tlaminator Avatar asked Nov 02 '15 17:11

tlaminator


People also ask

How split() function works in JavaScript?

split () Function in JavaScript | How split () Function Works in JavaScript? JavaScript provides us many string methods to modify our current string according to the requirement we have split () method is one of them. Split function in JavaScript is used to split a string.

How do you split a string into an array in JavaScript?

JavaScript | String split() str.split() function is used to split the given string into array of strings by separating it into substrings using a specified separator provided in the argument. The syntax of the function is as follows: str.split(separator, limit)

What are the arguments of split() function in C++?

Below are the arguments of split () function: 1 Separator: This argument is used as a string separator. it will point to the string where we need to split the string. 2 Limit: This argument is used to define the number of a split. This is optional. If we reach this limit and still the... More ...

What is Big O notation in JavaScript?

Big O Notation in JavaScript. In practice, we use Big O Notation to classify algorithms by how they respond to changes in input size, so algorithms with the same growth rate are represented with the same Big O Notation. The letter O is used because the rate of growth of a function is also called order of the function.


1 Answers

With an empty delimiter argument, split is essentially equivalent to:

var len = string.length;
var result = Array(len)
for (i = 0; i < len; i++) {
    result[i] = string[i];
}

This is O(len).

With a delimiter, it becomes O(string.length * delimiter.length), because at each step in the loop it has to test whether there's a match for delimiter.

like image 63
Barmar Avatar answered Oct 11 '22 18:10

Barmar