PolygonMesh triangulation... ?
-
BUT.. that is not the point I was making. You do not need to mess with an index, in order to iterate the members of an Enumerable collection.
Restated and simplified, as this:
for t in triplets t.each { |pt| pt.transform!(tra) } end
is faster and more readable (better practice) than:
for i in 0...triplets.size triplets[i].each { |pt| pt.transform!(tra) } end
Why faster?
- No calling the
size
method at the beginning. - No instantiation of a
Range
object via the...
operator - No need to call the
[]
method during each iteration.
There is no sense in using a index when you want the members of the enumerable collection.
Because, thefor
loop can directly serve up each enumerable member in turn, without the need to maintain an index variable on the Ruby side.(Of course the C-side implementation using for over there does use an iterator, but the C-side does not need to expose the iterator to the Ruby side.)
The
for
construct is not a method it's built into Ruby. And it does not create a new scope during each iteration. I image that other built-in looping constructs (while
,until
) can also be fast. - No calling the
-
@fredo6 said:
@anton_s said:
I think that each loop is slower than for loop. That's why I used for loop.
Not so sure in Ruby 2.x. See this interesting benchmark.
It is also said that the fastest is the
while
loop, when this is appropriate.Well that is interesting. Seems they optimized
while
andeach
, but notfor
.
So now we have a quandary if we publish for older SketchUps, with older Ruby. -
IN Ruby 1.8 for loops used to be faster - at least in the tests I performed on my extensions. But Ruby 2.0 swapped that around.
In any case - you don't really know until you profile your specific case.
Advertisement