Both Java and python (talking about CPython only) are interpreted to Java and CPython bytecode respectively. Both bytecodes are then interpreted by their respective virtual Machines (JVM & Cpython VM). (Here I am ignoring the JIT compilation part which kicks in after 10K runs.)
I have 2 questions regarding this:
- Why does Java compilation to java bytecode take so much time as compared to python? In java, compilation is an explicit step while in python it happens at runtime.
- Why is there no noticeable difference between the first run and the nth run of python when in the first run compilation to CPython bytecode is done and cached in .pyc files which is used in all successive runs. Is this bytecode compilation really an almost zero cost task in python?
Although it plays a big role in the runtime, I suppose static vs dynamic typing shouldn't play too big a role during the compilation and should not be the only reason for this difference in timings. Also, I think in both the implementations, some optimisation is done during the bytecode generation.
Is there something that I am missing here? (I do not have much experience working in Java.)
Update:
I actually did time profiling for python first run and later runs and found that statement 2 is wrong. There is a very noticeable difference when running a large python file.
Approach was simple. Created a large file with repeated lines of
a = 5
b = 6
c = a*b
print(str(c))
Then imported it to file large.py and ran time python large.py
First run result:
python large.py 1.49s user 0.33s system 97% cpu 1.868 total
Second run result:
python large.py 0.20s user 0.08s system 90% cpu 0.312 total
After deleting the __pycache__ folder:
python large.py 1.57s user 0.34s system 97% cpu 1.959 total
So basically in python also, the compilation to bytecode is a costly process, just that it's not as costly as in java.