Skip to content
Advertisement

Why time taken to execute code changes with one line?

This is my first code:

JavaScript

This is my second code:

JavaScript

This is my third code:

JavaScript

I don’t understand why replacing s with set(s) in 4th line takes less time to execute and replacing with set(s[:]) is even more better than the other two statements.

Can anyone help me to know why this happens?

Advertisement

Answer

After performing %timeit I found that @Barmar observation is correct. You should perform timeit on these function. set(s[:]) is expensive as compared to set(s)

For these 4 functions:

JavaScript

I got following output:

JavaScript

Also fastest method to check anagram will be XOR operator.

JavaScript

Performance: 667 ns ± 2.54 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

Advertisement