compilationjuliadynamic-compilation

Performance of the first vs second call of a function


Consider the following piece of code (Julia)

bar(x) = for i = 1:9999 x+x*x-x+x end # Define the "bar" function
print("First try: "); @time bar(0.5)
print("Second try: "); @time bar(0.5)
bar(x) = for i = 1:9999 x+x*x-x+x end # Redefine the same "bar" function
print("Third try: "); @time bar(0.5)
print("Fourth try: "); @time bar(0.6)

The output is

First try: elapsed time: 0.002738996 seconds (88152 bytes allocated)
Second try: elapsed time: 3.827e-6 seconds (80 bytes allocated)
Third try: elapsed time: 0.002907554 seconds (88152 bytes allocated)
Fourth try: elapsed time: 2.395e-6 seconds (80 bytes allocated)

Why is the second (and fourth) try so much faster (and take up less memory) than the first (and third) try?


Solution

  • Julia has, I understand, a just-in-time compiler. So the first (and third) run is compiling the code (with the allocations needed for that) and the second (and fourth) runs are just running the previously compiled code