javapythonperformancejython

Calling Python Functions from Java (Without Jython, because it is too slow.)


I need to be able to call Python functions from Java, and get the return of those functions, which should be primitives only.
I also don't need to access Java objects in Python or other stuff like that.
But, most of all, I need speed. I need to be able to load the script at the start of my application and then call some functions at different time-intervals, which can sometimes get really tiny (30-40 times per second).
That's the main-reason why I don't think that Jython will work for me: It has all kinds of stuff that I don't need, and is incredibly slow.

So, those are the constraints/requirements I have:

Do you guys know about another way to simply call Python functions in a pre-loaded script (So that the script does not have to be loaded again and again for each function call)?

(PS: I do not think that this is a duplicate as I searched quite a lot and all links I found did not answer my question (For example Calling Python in Java?) )


Solution

  • You could write some JNI code to embed the CPython interpreter.

    You could write a Python program that will run as a daemon (or web service or whatever) and connect to it via some sort of networking. I am intentionally vague here since it is such a broad question with any number of possibilities.

    I don't know that either of the above will actually be faster than calling in to Jython. Note that you can load the Jython interpreter once and (re)use it for each function call.

    What if you rewrote your Python function in Java? You can even load it dynamically, if that is the reason you are trying to combine multiple languages. Alternatively, Java8 comes with a (new) JavaScript engine. You could use JavaScript instead of Python.