Python vs Java, Measured — Including the Run That Gave the Wrong Answer
Asking which is better has no answer, but every part of the question that can be measured was measured here on one machine — Python 3.13.15 against Java 21.0.12. Python started three times faster and used a tenth of the memory. Java ran a tight arithmetic loop 110 times faster and returned a number that was wrong by a factor no one would notice. On a realistic task the gap between them was 1.7 times.
"Python vs Java, which is better" is not a question with an answer, and every page that gives you one is selling something. What it does have is parts that can be measured, so all four of them were — the same work, written twice, on one machine: Python 3.13.15 against Java 21.0.12, eight cores, stock settings, no tuning on either side.
Three of the four went the way the folklore says. The fourth is the reason this article exists: Java won a benchmark by a factor of 110 and returned an answer that was wrong by a factor of four and a half thousand, without a warning, an exception or a log line.
Startup: Python, by three times
Ten runs each of a program that prints one word, best to worst in milliseconds:
python: 7 7 7 7 7 7 7 7 8 10
java: 21 21 21 21 22 22 23 25 26 33
java+cds: 19 19 20 20 20 20 21 21 22 23
Python starts in about 7 ms, Java in about 22 ms. That is a real advantage and it matters for anything you invoke from a shell script or a CI step a thousand times a day.
It is also worth saying what it is not. "The JVM takes seconds to start" is folklore from a different decade — 22 ms is fast by any standard, and the third row is the JVM's own class-data archive (-XX:ArchiveClassesAtExit), which bought another 2 ms and is not the order-of-magnitude fix people hope for. What costs seconds on the JVM is a framework building a dependency graph, not the runtime coming up.
A tight loop: Java, by 110 times
Summing i * i for fifty million integers. Java warmed up first — five throwaway runs before anything was recorded, because the just-in-time compiler needs to have seen the loop:
static long work(int n) {
long acc = 0;
for (int i = 0; i < n; i++) acc += (long) i * i;
return acc;
}
def work(n):
acc = 0
for i in range(n):
acc += i * i
return acc
java run 1: 18 ms run 2: 18 ms run 3: 17 ms
python run 1: 1978 ms run 2: 1941 ms run 3: 2068 ms
A hundred and ten times. This is the number that gets quoted, and on its own terms it is honest: an interpreted loop doing integer arithmetic is the worst case for CPython and close to the best case for a JIT, which compiles that loop into a handful of machine instructions and keeps the accumulator in a register.
Then look at what each one printed.
java acc -4529445843202100544
python acc 41666665416666675000000
The wrong answer
Python is right. The closed form for the sum of squares gives 41,666,665,416,666,675,000,000, which matches its output exactly. Java's number is that value wrapped around to 64 bits — verified by taking the exact answer modulo 2⁶⁴ and getting -4529445843202100544 back.
The true answer is 4,518 times larger than Long.MAX_VALUE. Java's long overflowed roughly four and a half thousand times over, and said nothing at all. That is not a bug, it is the specification: the JLS states flatly that "the integer operators do not indicate overflow or underflow in any way". Meanwhile Python's documentation needs four words for its side of it — "Integers have unlimited precision" — and that is exactly what you are paying for in the 1,941 ms.
Common mistake
Reporting the 110x without the accumulator. The two programs did not do the same work: one computed the answer and one computed a wrong answer quickly. A benchmark is only a comparison if both sides are correct, and checking the output is how you find out — which is an argument for printing it even when you think you know what it will be.
If you want Java to be right here, BigInteger or Math.addExact will do it — the first is slow and the second throws. Neither was measured for this article, unlike everything else on this page; they are the two names worth knowing, not a result. What was measured is the default, and the default is silence.
The same loop, the way Python is actually written
Nobody writes that Python loop. They reach for NumPy, which is C behind an array API:
i = np.arange(n, dtype=np.int64)
acc = int((i * i).sum())
numpy run 1: 383 ms run 2: 105 ms run 3: 103 ms
numpy acc -4529445843202100544
103 ms — nineteen times faster than the Python loop and six times slower than Java. Worth noting that the first run cost 383 ms, which is the array allocation and warm caches, exactly the kind of thing that makes a single-run benchmark lie.
And look at the accumulator. NumPy returned Java's wrong answer, to the digit, because int64 is a fixed-width machine integer and NumPy's types are the machine's rather than Python's. Speed and overflow arrived together: the moment Python got fast, it inherited the same silence.
A realistic task: the gap collapses
A tight arithmetic loop is a microbenchmark. Counting words in a 43.2 MB file — 400,000 lines, 4.8 million words — is closer to work, and both languages have a good tool for it in the standard library: collections.Counter and a HashMap with merge.
java run 1: 421 ms run 2: 397 ms run 3: 309 ms
python run 1: 653 ms run 2: 551 ms run 3: 562 ms
1.7 times, not 110. Both found 3,000 distinct words and both agreed on the most common one at word2562=1727.
The reason is that neither language is doing the work in the language. Counter.update is C and HashMap.merge is JIT-compiled Java, so the comparison becomes two optimised hash tables and a file read, and the interpreter overhead is a small share of a bigger job. This is the shape most real programs have, which is why the 110x is a fact about loops rather than a fact about languages.
Memory: Python, by ten to twenty-six times
Peak resident set size for the same two programs, measured with /usr/bin/time:
hello world java 76,312 KB python 7,596 KB 10x
word count java 229,588 KB python 8,700 KB 26x
word count java -Xmx64m 136,680 KB 15x
This is Python's largest win and it is structural. The JVM reserves a heap and manages it, which is what buys the throughput above; CPython asks the operating system for memory as it goes. A JVM process therefore has a floor of tens of megabytes before your code exists.
The third row is the one to act on. Capping the heap at 64 MB cut resident memory by 40 percent and the wall clock did not move — 0.94 s either way. If you are packing JVM services into containers, the default heap is sized for the machine rather than for the container, and what a JVM does with a memory limit is worth knowing before the scheduler decides for you.
What is in the box
Speed is not the only thing a comparison should measure, and the next one is not close. A 17.2 MB JSON file with 200,000 objects, read with nothing installed:
with open("data.json") as f:
d = json.load(f) # 224-246 ms over three runs, 200,000 rows
The Java equivalent does not compile, because there is no Java equivalent:
Json.java:1: error: package javax.json does not exist
import javax.json.Json;
Asked for three of the names people expect — javax.json, jakarta.json, org.json — the JDK reports all three absent. JSON is the format the whole industry moved to and Java still has none of it in the standard library, so every Java project that touches HTTP starts with a dependency choice (Jackson, Gson, JSON-B) and the supply-chain surface that comes with it. Python's answer is import json.
The same asymmetry shows up in the small. The word-count programs measured above are 10 non-blank lines of Python and 18 of Java — a ratio that will not hold for every task, and does hold often enough to be why prototypes get written in Python.
So which is better?
The measurements answer narrower questions, and those have answers:
- Starting processes constantly — Python, by three times.
- Numeric loops you cannot vectorise — Java, by two orders of magnitude, if you get the types right.
- Packing many small services into memory — Python, by ten times or more, and cap the JVM heap if it has to be Java.
- Work that leans on built-in data structures — near enough a draw, at 1.7x.
- Arithmetic that might exceed 9.2 × 10¹⁸ — Python, for free. Java, if you ask for
BigIntegerexplicitly and remember why. - Reading JSON with nothing installed — Python. The JDK has no JSON API at all.
What none of it measures is the part that usually decides: the libraries you need, whether a type error should be found by a compiler or by a test, and what the people around you already read fluently. Threads against processes is a sharper version of that trade-off, since the GIL shapes Python concurrency in a way the JVM's does not. And if the JVM side is new to you, what the JDK, the JRE and the JVM each are is the thing to read before any of these numbers mean much; the same goes for how a HashMap is actually built, since it is doing the work in the only benchmark here that resembles a program.
[!TAKEAWAY] Print the result of your benchmark, not just its time. Java beat Python by 110 times on a loop and returned a number 4,518 times past what a
longcan hold, without a word of complaint — and NumPy, being fast the same way, was wrong in exactly the same digits. The fastest wrong answer is still wrong, and the only thing that catches it is looking.
Frequently asked questions
- Is Java always faster than Python?
- No, and the benchmark that says so is usually the one that flatters it most. A tight arithmetic loop is the workload where an interpreter is punished hardest, and the gap measured there was 110x. The same comparison on a task built out of each language's own optimised machinery — counting words with Counter against HashMap — came out at 1.7x. Pick your benchmark and you can prove either sentence.
- Why does Python use so much less memory?
- Because the JVM reserves a heap up front and manages it itself, while CPython asks the operating system for memory as it needs it. That design buys the JVM throughput and costs it a floor: hello world measured 75 MB resident against Python's 7.4 MB. Capping the heap pulls it down substantially, and on this workload it cost nothing in time.
- Does Python's arbitrary-precision integer slow it down?
- Yes, and that is part of what the 110x is paying for. Every Python int is an object that can grow, so an addition is a function call with allocation rather than one machine instruction. Java's long is 64 bits in a register, which is why it is fast and why it wraps around when the value gets too big.
- Which should I learn first?
- Whichever the work in front of you is written in — the question is less consequential than it looks, because the second language costs a fraction of the first. If there is genuinely no work in front of you: Python if you want to see results the same afternoon, Java if you want to understand what the machine is doing, since its sharp edges are visible rather than hidden.
- Are these numbers valid for my machine?
- The ratios travel better than the numbers. Everything here was measured on one eight-core Linux container with stock settings and no tuning, so the milliseconds are illustrations. What should reproduce anywhere is the shape: Python ahead on startup and memory, Java far ahead on tight numeric loops, and the two close together on work that leans on built-in data structures.