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?

snow
  • 455
  • 2
  • 13
  • 28
  • 1
    This is the perfect question to try out yourself; `import timeit; timeit.timeit(function)`. – Adam Barnes Jul 04 '16 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? – jonrsharpe Jul 04 '16 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. – snow Jul 04 '16 at 14:55
  • Have a look at : http://stackoverflow.com/questions/2214651/efficient-python-array-with-100-million-zeros – Destrif Jul 04 '16 at 14:55

1 Answers1

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.

tobias_k
  • 81,265
  • 12
  • 120
  • 179