Performance of nested Loop in GoLang

Hi All,
We are iterating through an array of integer in a nested loop in Go - 1.7.3 . We are having similar code running in Java 1.8.x . Both Go and Java is running on Windows Platform . We found execution time in java is faster than that of Go .

I am posing code snippet which is responsible for looping operation . It will be of great help , if you can explain why Java iterations on integer array performs better than that of Go.

My code snippet is below

startTime := time.Now()
for a := 0; a < arrLength; a++ {
for b := 0; b < arrLength-a-1; b++ {
if unsortedArray[b] > unsortedArray[b+1] {
temp := unsortedArray[b]
unsortedArray[b] = unsortedArray[b+1]
unsortedArray[b+1] = temp
}
}
}
fmt.Println(time.Since(startTime))

1 Like

It would be quite helpful to show the Java code you are comparing this with.

May I also suggest that you share your Go code with Go playground.

In Go you can get rid of the temp when switching elements which might spare a few bound checks.
And you might might consider a better algorithm :slight_smile:
V.

Thanks for your response . We are using same algo in Java and trying to do an orange to orange comparison. We also tested other cases like REST service in Java vs REST service in go etc. In these cases go performs better than Java , but specifically we observed , in loop iteration , java performs better than GO . That’s why trying to identify root cause of slowness in case of iterations / loops. We also took separate measurement for
if unsortedArray[b] > unsortedArray[b+1] {
temp := unsortedArray[b]
unsortedArray[b] = unsortedArray[b+1]
unsortedArray[b+1] = temp
}
, there Java and Go performs almost similarly . So , we are suspecting loop iterations as cause of slowness.

long startTime = System.currentTimeMillis();
for(int a=0;a<arraySize-1;a++)
{
for(int b=0;b<arraySize - a -1;b++)
{
if(dataArray[b]>dataArray[b+1])
{
int swapVar = dataArray[b];
dataArray[b] = dataArray[b+1];
dataArray[b+1] =swapVar;
}
}
}
long endTime = System.currentTimeMillis();

Hi!
It would be helpful if you could provide some additional data such as the number of elements in the array/slice for your tests and how long it takes in Java vs Go.

See the compiled code to find the differences.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.