just thought I would share with the community what I learned today; that list comprehension in Jython 2.7 is not faster. If youre like me, you've probably heard a lot that list comprehension is faster and that you should use it (but if you dig deeper, in using actual python 3.x , its also not always faster, only in simple scenarios it helps).
What I found is that in jython its much slower, even for simple operations.
using a for loop in this test showed its about 2x as fast as list comprehension
here is the code if you want to try yourself:
import timeit
MILLION_NUMBERS = list(range(1000000))
def list_comprehension(MILLION_NUMBERS):
return [number for number in MILLION_NUMBERS if not number % 2]
def for_loop(MILLION_NUMBERS):
output = []
for element in MILLION_NUMBERS:
if not element % 2:
output.append(element)
return output
def list_comprehension_simple(MILLION_NUMBERS):
return [number + 1 for number in MILLION_NUMBERS]
def for_loop_simple(MILLION_NUMBERS):
output = []
for element in MILLION_NUMBERS:
output.append(element +1 )
return output
t = timeit.Timer(lambda: list_comprehension(MILLION_NUMBERS))
print("total time for list_comprehension: ", (t.timeit(100)))
t = timeit.Timer(lambda: for_loop(MILLION_NUMBERS))
print("total time for for_loop: ", (t.timeit(100)))
print("simple:")
t = timeit.Timer(lambda: list_comprehension_simple(MILLION_NUMBERS))
print("total time for list_comprehension_simple: ", (t.timeit(100)))
t = timeit.Timer(lambda: for_loop_simple(MILLION_NUMBERS))
print("total time for for_loop_simple: ", (t.timeit(100)))