mk-tool
mk-tool

Reputation: 345

The time complexity of the map function

I heard the calculation amount of map function is O(1). But I can't understand the reason.

Upvotes: 0

Views: 9077

Answers (2)

Ahmed Baruwa
Ahmed Baruwa

Reputation: 9

The inbuilt map method shares the input iterable across the CPU cores. For an iterable of size n, the average running time would be Θ(n/num_cpu_cores)

Upvotes: 0

user9761835
user9761835

Reputation:

If I understand your question correctly, O(1) is the complexity of accesing one item. Array.map() in JS passes the function the current value and iterates through all of them, and takes the return value of the function and inserts it into the new array.

Therefore, the function loops through every object in the array, having a complexity of O(n).

For example:

[1, 2, 3].map(function (item) { return item + 1; });

Said function takes one item at a time, accessing the array n times (3).

EDIT: Looks like I misunderstood your question, my bad.

Upvotes: 1

Related Questions