It's impossible to make blanket statements about optimizations like
this. It depends on many factors, including:
- The types of slices you're using
- Hardware peculiarities
- Optimizations in the Go compiler you're using (which change as it matures)
This case is absolutely not worth "optimizing" in the general case;
only if it's provably a bottleneck in a very tight loop should you
even spend any time thinking about it.
In that case, testing.B is your friend.
Here is a simple benchmark in which the range version is faster than
the index version, BUT only for
- my computer and Go compiler
- a particular workload (a running sum)
- a particular slice type ([]int)
http://play.golang.org/p/YikjtG7dXOI make no claims about the general relative performance of for/range
vs traditional for.
-Caleb
On Wed, Apr 9, 2014 at 10:59 PM, William Kennedy
wrote:
I have read the spec on the use of the keyword range:
http://golang.org/ref/spec#RangeClauseUsing this code as a reference for my questions:
func Range() {
for _, value := range data {
Foo(value)
}
}
func Index() {
for index := 0; index < len(data); index++ {
Foo(data[index])
}
}
Shouldn't using an index to access each value from a slice be more efficient
than using a for-range and creating a copy. Especially if value is based on
a user-defined type with a few fields?
What is the advantage of using for-range over using a for with an index?
Is the answer that the for-range is simpler, and less error prone. Plus it
eliminates the bounds checking that Go is executing with each call to
data[index]?
--
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+unsubscribe@googlegroups.com.
For more options, visit
https://groups.google.com/d/optout.--
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+unsubscribe@googlegroups.com.
For more options, visit
https://groups.google.com/d/optout.