List comprehension is much slower in jython

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)))
1 Like

running the same in python 3.12 , its really about the same

in 3.9, its a bit faster but not much

Seems to be Jython specific, comprehensions are faster in Python 2.7 as well.

Python 2.7:

kevin@DV-55J5DY3-LT:~$ python2.7 comptest.py
('total time for list_comprehension: ', 1.994236946105957)
('total time for for_loop: ', 2.7266299724578857)
simple:
('total time for list_comprehension_simple: ', 1.7277748584747314)
('total time for for_loop_simple: ', 3.0167899131774902)

Jython 2.7:

kevin@DV-55J5DY3-LT:~$ jython comptest.py
('total time for list_comprehension: ', 9.468000173568726)
('total time for for_loop: ', 4.379000186920166)
simple:
('total time for list_comprehension_simple: ', 10.111999988555908)
('total time for for_loop_simple: ', 5.130000114440918)

That's it, you'll have to rewrite ignition in C.

5 Likes

Straight to jail :upside_down_face:

6 Likes

I'm sure if you start working on rewriting in Rust you'll have something ready by Ignition 12.1

1 Like

Is there a rusthon ?

There is, currently v0.3.0:

Unfortunately, it's not all that performant in its current state.

2 Likes