This days I'm practicing with Go a little writing sort algorithms and
discovered strange thing:
in a bubble sort (don't leaf :D) there are two loops one inside another,
just like this:
length := len(array)
for j := 1;j<length-1; j++ {
for i:=0; i<length-j; i++ {
if array[i]>array[i+1] {
Swap(&array,i,i+1)
}
}
}
for i:=0; i<length-j; i++ {
if array[i]>array[i+1] {
Swap(&array,i,i+1)
}
}
}
Just like always (in other programming languages) I assign the length of an
array just before the loop to not execute the length calculation repeatedly
BUT, when I made some tests, results that in GO, putting len(array) inside
the loop make it FASTER !!!
A code with a len() function is this one:
for j := 1;j<len(*array)-1; j++ {
for i:=0; i<len(*array)-j; i++ {
if (*array)[i]>(*array)[i+1] {
Swap(array,i,i+1)
}
}
}
if (*array)[i]>(*array)[i+1] {
Swap(array,i,i+1)
}
}
}
Average execution time with a length variable 526000 microseconds sorting
an array of 10000 int elements
Average execution time with a len() function 508000 microseconds sorting
an array of 10000 int elements
I have made tests a lot o times on the same machine, an the result is
always the same(+-).
So can somebody explain WHY is it faster to use len(array) inside the
loop? What about function call, stack allocation ?
--
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 [email protected].
For more options, visit https://groups.google.com/groups/opt_out.