The performance comparation of Golang and Java

433 views
Skip to first unread message

Topget

unread,
Jan 24, 2019, 9:21:14 PM1/24/19
to golang-nuts
I have tested several simple functions with Golang and Java. To my surprise, Java sometimes is faster than Golang(especially in recursive function and some function in standard library such as math/rand.Rand). I wonder why. Here is some code I used for test and the result.

Golang code:

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func calPi(pointCount int) float64 {
    inCircleCount := 0

    var x, y float64
    var Pi float64

    for i := 0; i < pointCount; i++ {
        x = rand.Float64()
        y = rand.Float64()

        if x*x+y*y < 1 {
            inCircleCount++
        }
    }

    Pi = (4.0 * float64(inCircleCount)) / float64(pointCount)

    return Pi
}

func fibonacci(c int64) int64 {
    if c < 2 {
        return c
    }

    return fibonacci(c-2) + fibonacci(c-1)
}

func main() {
    rand.Seed(time.Now().Unix()) // 初始化随机数

    fmt.Printf("Test 1\n")

    startTime := time.Now()

    result := 0.0

    for i := 0.0; i < 1000000000; i = i + 1 {
        result += i * i
    }

    endTime := time.Now()

    fmt.Printf("Result: %v\n", result)

    fmt.Printf("Duration: %v\n", endTime.Sub(startTime))

    fmt.Printf("Test 2\n")

    startTime = time.Now()

    resultInt := fibonacci(50)

    endTime = time.Now()

    fmt.Printf("Result: %v\n", resultInt)

    fmt.Printf("Duration: %v\n", endTime.Sub(startTime))

    fmt.Printf("Test 3\n")

    startTime = time.Now()

    result = 0.0

    for i := 0.0; i < 100000000; i = i + 1 {
        result += rand.Float64()
    }

    endTime = time.Now()

    fmt.Printf("Result: %v\n", result)

    fmt.Printf("Duration: %v\n s", endTime.Sub(startTime))

    fmt.Printf("Test 4\n")

    startTime = time.Now()

    result = calPi(100000000)

    endTime = time.Now()

    fmt.Printf("Result: %v\n", result)

    fmt.Printf("Duration: %v s\n", endTime.Sub(startTime))

}


the result:

Test 1
Result: 3.333333328333552e+26
Duration: 1.449212507s
Test 2
Result: 12586269025
Duration: 1m31.645050682s
Test 3
Result: 4.999483069673434e+07
Duration: 2.534121566s
 sTest 4
Result: 3.14147056
Duration: 5.036491495s s

Java code:

public class Performance {

public static double calPi(int pointCount) {
int inCircleCount = 0;

double x, y;
double Pi;

for (int i = 0; i < pointCount; i++) {
x = Math.random();
y = Math.random();

if (x * x + y * y < 1) {
inCircleCount++;
}
}

Pi = (4.0 * inCircleCount) / pointCount;

return Pi;
}

public static double cal(double a, double b, double c) {
return a * b / (c + 1) + a;
}

public static long fibonacci(long c) {
if (c < 2)
return c;
return fibonacci(c - 2) + fibonacci(c - 1);
}

public static void main(String[] args) {

System.out.println("Test 1");

long startTime = System.currentTimeMillis();

double result = 0.0;

for (double i = 0.0; i < 1000000000; i = i + 1) {
result += i * i;
}

long endTime = System.currentTimeMillis();

float duration = (float) (endTime - startTime) / 1000;

System.out.println("Result: " + result);
System.out.println("Duration: " + duration + " s");

System.out.println("Test 2");

startTime = System.currentTimeMillis();

long resultInt = fibonacci(50);

endTime = System.currentTimeMillis();

duration = (float) (endTime - startTime) / 1000;

System.out.println("Result: " + resultInt);
System.out.println("Duration: " + duration + " s");

System.out.println("Test 3");

startTime = System.currentTimeMillis();

result = 0.0;

for (double i = 0; i < 100000000; i = i + 1) {
result += Math.random();
}

endTime = System.currentTimeMillis();

duration = (float) (endTime - startTime) / 1000;

System.out.println("Result: " + result);
System.out.println("Duration: " + duration + " s");

System.out.println("Test 4");

startTime = System.currentTimeMillis();

result = calPi(100000000);

endTime = System.currentTimeMillis();

duration = (float) (endTime - startTime) / 1000;

System.out.println("Result: " + result);
System.out.println("Duration: " + duration + " s");

}
}


result:

Test 1
Result: 3.333333328333552E26
Duration: 2.948 s
Test 2
Result: 12586269025
Duration: 60.816 s
Test 3
Result: 4.9999087237930864E7
Duration: 2.448 s
Test 4
Result: 3.14147284
Duration: 4.786 s


The difference of Test 2 results really shocked me!

Jimmy Wong

unread,
Jan 24, 2019, 9:47:48 PM1/24/19
to golang-nuts

Rodolfo

unread,
Jan 24, 2019, 9:51:58 PM1/24/19
to Topget, golang-nuts
You only checking speed, you need to check memory and cpu too. Java is faster because it allocate too much memory and If your tests during a lot of time you will see the performance degrade, Go in other hand grow and use less memory. My explanation is not complete, But I am a Java developer and all system that I did with Java, when I put database driver, serialization and etc, performs much lower than Go.

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Ian Lance Taylor

unread,
Jan 24, 2019, 9:57:06 PM1/24/19
to Topget, golang-nuts
On Thu, Jan 24, 2019 at 6:21 PM Topget <topge...@gmail.com> wrote:
>
> I have tested several simple functions with Golang and Java. To my surprise, Java sometimes is faster than Golang(especially in recursive function and some function in standard library such as math/rand.Rand). I wonder why. Here is some code I used for test and the result.

Because goroutines start with a small stack that grows as needed,
deeply recursive functions will tend to have somewhat worse behavior
the first time they are called.

Ian

Dmitry Ponyatov

unread,
Jan 24, 2019, 10:42:11 PM1/24/19
to golang-nuts
You should also take into account resource consumption, primarily RAM usage (and also CPU usage for runtime action itself: not linked with application logic).

So you should normalize your benchmarks by RAM usage, and it will give you 100x of golang efficiency. Java critically requires 2G of RAM to be practically useful.

I bought cheap BDF 10" netbook, and some really dumb chinese engineer used Android5 on 512M RAM with crap ATM7029 SoC. I can use it only one way: Termux + golang (and very small programs with clang compiling). If I try to run any standard app like YouTube or even system configuration, Linux kernel runs memory killer, and I need to wait up to a minute just to repeat my try to run the app.

PS: Does anybody has some experience to help me to find SDK and manuals for porting native Linux on ATM70x9 SoCks ?

Pat Farrell

unread,
Jan 24, 2019, 10:56:03 PM1/24/19
to golang-nuts
On Thursday, January 24, 2019 at 9:21:14 PM UTC-5, Topget wrote:
I have tested several simple functions with Golang and Java. To my surprise, Java sometimes is faster than Golang(especially in recursive function and some function in standard library such as math/rand.Rand).


What others have  already said. Plus, the JVM is an impressive bit of work. The runtime optimization is first class and does an amazing job.

Benchmarks always lie. Mostly because they ask the wrong question. You don't care if one program or another is 5% faster. Software engineering is about the cost over the life-cycle, that includes hardware to run it on, and all the software engineering effort to implement and maintain the code. 

Karthik Krishnaswamy

unread,
Jan 24, 2019, 11:28:16 PM1/24/19
to Ian Lance Taylor, Topget, golang-nuts
I am just curious to understand what is the best possible way to increase the execution speed of this particular program ? I am still learning go though :)

Ian Lance Taylor

unread,
Jan 24, 2019, 11:48:54 PM1/24/19
to Karthik Krishnaswamy, Topget, golang-nuts
On Thu, Jan 24, 2019 at 7:01 PM Karthik Krishnaswamy
<karthik.kri...@gmail.com> wrote:
>
> I am just curious to understand what is the best possible way to increase the execution speed of this particular program ? I am still learning go though :)

To speed up that particular program, don't use recursive Fibonacci.
The recursive function that you wrote has complexity O(2 ** N). Write
a simple loop, complexity O(N).

Ian

Michael Jones

unread,
Jan 25, 2019, 1:45:32 AM1/25/19
to Ian Lance Taylor, Karthik Krishnaswamy, Topget, golang-nuts
Also...pseudo-random number generation is not a specific computation; there are many ways to do it--some faster some slower, some better some worse. If you want to time a general poisson disc simulation you would be better with a grid than calls to rand() because now you are testing the speed of the chosen random number generator.

For comparison, your fmt.Println(calPi(100000000)) with the standard (locking) prng on my notebook:

3.14151812
real 0m5.123s

versus a one-thread high-quality prng:

3.14154348
real 0m1.395s

The speedup shows that you are just testing random number generation speed.

The same computation with a grid of pointCount points...

root := math.Sqrt(float64(pointCount))
d := 2 / root
for x := -1.0; x < 1.0; x += d {
for y := -1.0; y < 1.0; y += d {
if x*x+y*y < 1 {
inCircleCount++
}
}
}

...gives:

3.14158668
real 0m0.170s

So, 5.123 or 1.395 or 0.170 seconds based on how the sample points are calculated. Performance testing is hard.

Michael
--
Michael T. Jones
michae...@gmail.com

Sebastien Binet

unread,
Jan 25, 2019, 2:16:21 AM1/25/19
to Michael Jones, Ian Lance Taylor, Karthik Krishnaswamy, Topget, golang-nuts
Also-rans: the global math/rand functions are thread safe (drawing a random number is protected by a mutex.)
If the Java one isn't thread safe, you are comparing apples with oranges.

Try creating a local rand.Rand and see what gives.

HTH,
-s

sent from my droid

Haddock

unread,
Jan 25, 2019, 4:49:17 AM1/25/19
to golang-nuts
This algorithm is quite fast and corect:

public static int fibo(int n) {
    int t = 1;
    int result = 0;

    while (n-- > 0) {
        result = t - result;
        t = t + result;
    }

    return result;
}

Am too busy to convert the code to Go, but it should be easy.

er...@tibco.com

unread,
Jan 25, 2019, 6:36:04 PM1/25/19
to golang-nuts
Microbenchmarks can always be misleading.

My take on Go vs. Java performance:

The key point is that optimizing the developer's time completely swamps a lot of other limitations. This partly explains why Python and Javascript continue to see wide use, in spite of their performance concerns.

Eric.

Bakul Shah

unread,
Jan 25, 2019, 7:00:10 PM1/25/19
to Ian Lance Taylor, Karthik Krishnaswamy, Topget, golang-nuts

> On Jan 24, 2019, at 8:48 PM, Ian Lance Taylor <ia...@golang.org> wrote:
>
> On Thu, Jan 24, 2019 at 7:01 PM Karthik Krishnaswamy
> <karthik.kri...@gmail.com> wrote:
>>
>> I am just curious to understand what is the best possible way to increase the execution speed of this particular program ? I am still learning go though :)

General advice to Karthik: use micro-optimizations only as the last resort. Improve developer's execution speed :-)

> To speed up that particular program, don't use recursive Fibonacci.
> The recursive function that you wrote has complexity O(2 ** N). Write
> a simple loop, complexity O(N).

There is a O(log N) recursive algorithm but probably not worth it when you can only compute 64bit size fibonacci numbers (up to 91).

Topget

unread,
Jan 28, 2019, 8:16:03 PM1/28/19
to golang-nuts
It will be better if someone could give me the example(s) to show the advantage of Golang (vs Java). Thanks.

在 2019年1月25日星期五 UTC+8上午10:21:14,Topget写道:

Rodolfo

unread,
Jan 28, 2019, 8:31:00 PM1/28/19
to Topget, golang-nuts
In my poor opnion:

1. Golang is a programming language that not need a virtual machine, It communicate directly with kernel, making use of all resource hardware better than Java.

2. Golang uses goroutines that consume only 2k of memory instead of 2MB(minimun) of threads used in Java.

3. With Golang the dilema: "Write once run anywhere" is true, because you can do a cross compile and run your program in differents platforms with the same codebase.

4.  Golang offering everything do you need, without necessity to install any framework.

And many other qualities that I do not remember :)

Regards

Rodolfo Azevedo

Reply all
Reply to author
Forward
0 new messages