From: Victor Shepelev Date: 2006-06-02T05:47:51+09:00 Subject: Re: How use Profiling, a Quick Guide. From: Dave Howell [mailto:groups@grandfenwick.net] Sent: Thursday, June 01, 2006 11:36 PM > >>> * Large number of calls to .size and .length and .count_objects > >>> methods are a > >>> clue some nidjit somewhere is doing something really N^2 stupid > >>> like... > >>> for( i=0; i < container.count_objects(); i++) { > >>> } > >> > >> question_stack << "What exactly is stupid about that? And what's the > >> smart alternative? > > max=container.count_objects() > > for( i=0; i < max; i++) { > > } > > > > container.each.... > > OK, so "container.each" is presumably the smart alternative, and what > I'd instinctively use anyway, but I don't understand what it is about > "for( i=0; i < max; i++)" that makes it "really n^2 stupid." The point was: if you use some value repeatedly, it is generally smarter to pre-calculate it. Example: def get_some_value #some long calculation end (1..100).each{|i| puts i * get_some_value} The above code would call get_some_value 100 times. If it rans slowly and would return 100 same values, the much more smarter way would be v = get_some_value (1..100).each{|i| puts i * v} V.