简体   繁体   中英

Jython - is it faster to use Python data structures or Java ones?

I'm trying to understand whether and under what circs one should use Python classes and/or Java ones.

If making a specialist dictionary/Map kind of class, should one subclass from Python's dict, or from Java's HashMap or TreeMap, etc.?

It is tempting to use the Python ones just because they are simpler and sexier. But one reason that Jython runs relatively slowly (so it appears to me to do) seems to have something to do with the dynamic typing. I'd better say I'm not that clear about all this, and haven't spent nocturnal hours poring over the Python/Jython interpreter code, to my shame.

Anyway it just occurs to me that the Java classes might possibly run faster because the code might have to do less work. OTOH maybe it has to do more. Or maybe there's nothing in it. Anyone know?

The point of using Jython is that you can write Python code and have it run on the JVM. Don't ruin that by making your Python into Java.

If -- if -- it turns out that your data structure is too slow, you can drop-in replace it with a Java version. But that's for the optimisation stage of programming, which comes later.


I guess I should try to answer your question. I would guess that using native Java structures will be faster (because the JVM can infer more about them than the Python interpreter can), but that might be counterbalanced by the extra processing needed to interface with Jython. Only tests will tell!

Generally, the decision shouldn't be one of speed - the Python classes will be implemented in terms of Java classes anyway, even if they don't inherit from them. So, the speed should be roughly comparable, and at most you would save a couple of method calls per operation.

The bigger question is what you plan on doing with your class. If you're using it with Python APIs, you'll want to use the Python types, or something that behaves like them so that you don't have to do the work of implementing the entire Mapping protocol (only the bits your class changes). If you're using Java APIs, you will certainly need to meet the static type checks - which means you'll need to inherit from Java's classes.

If this isn't easy to answer in your situation, start with the Python ones, since you (correctly ;-) find them "simpler and sexier". If your class doesn't pass outside the boundaries of your project, then this should be trivial to change later if the speed really becomes an issue - and at that point, you might also be thinking about questions like "could it help to implement it entirely at the Java level?" which you've hopefully recognised would be premature optimisation to think about now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM