0

Is there any difference in terms of performance in doing this:

for i in range(T):  
      arr = [int(arr_temp) for arr_temp in input().strip().split(' ')]

and this:

for i in range(T):
    arr = input().strip().split(' ')
    arr = list(map(int, arr))

if yes, which is better?

4
  • 1
    This is the perfect question to try out yourself; import timeit; timeit.timeit(function). Commented Jul 4, 2016 at 14:53
  • Which bit are you interested in? Whether inlining the input makes a difference, or whether list(map(...)) performs differently to a list comprehension? Commented Jul 4, 2016 at 14:54
  • the first loop is there because i need to create T number of arrays. I need to know if using map() and converting each string array into int will increase performance as opposed to using nested loops to achieve the same. Commented Jul 4, 2016 at 14:55
  • Have a look at : stackoverflow.com/questions/2214651/… Commented Jul 4, 2016 at 14:55

1 Answer 1

2

According to IPython's %timeit function, map is a bit faster:

In [16]: s = ' '.join(map(str, range(1000)))

In [17]: %timeit [int(c) for c in s.split()]
10000 loops, best of 3: 171 µs per loop

In [18]: %timeit list(map(int, s.split()))
10000 loops, best of 3: 138 µs per loop

Tested with IPython 1.2.1 and Python 3.4.3 and with different input sizes (range(1000), range(10), and range(100000)).

Of course, the interesting question is: Is this part of the code slowing down your program (assuming that that's why you are asking, and not out of pure curiosity). Compared to, e.g., reading the input (from a file, I presume?), or doing calculations with the data, it might be pretty insignificant.

Sign up to request clarification or add additional context in comments.

4 Comments

And both are completely overwhelmed by the I/O input() from the user
Is this true for different input sizes? (I.e., no "crossing" in the growth functions for the two alternatives).
@joelgoldstick Depends, maybe the input is coming from a file piped into the script. But I agree that it probably does not matter too much.
@dfri Good point, checking... yes, seems to be pretty much linear in both cases.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.