From: Rick DeNatale Date: 2009-02-19T03:31:50+09:00 Subject: Re: Newbie - several array questions --00163630f2bfb3d612046335a291 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit On Wed, Feb 18, 2009 at 12:10 PM, Choi, Junegunn wrote: > > > > As long as you realize that inject() is always the most inefficient > > solution possible. > > > > Can you elaborate on your claim? How inefficient, like, by orders of > magnitude? Is it serious enough to affect the overall performance of a > typical ruby application? In a situation like this, I'd prefer the > code which uses 'inject', since it shows the intention of the > programmer more clearly and concisely, while the performance penalty - > 10% in my naive experiment - is irrelevant in this case. I agree that > we should be aware of the performance issues even when we're dealing > with a high-level language such as ruby, but your bold statement makes > me feel that you're trying to 'defend' your own code against the > others in some kind of a code contest. > I think that the statement that "inject() is always the inefficient solution possible", even if it were true, which I'm not at all sure it is, isn't particularly good advice. One of my buddy Kent Beck's more well known memes is "Make it run. Make it right, Make it fast." [1]. Although the roots of this advice can be traced back to Butler Lampson [2]. This advice is something that anyone who wants to be a software craftsman needs to take to heart. The order is important. First you make sure that the code runs, then you need to make it right. Making it right doesn't mean that it does the right thing, that's a large part of making it run, it mean's making the code clear and maintainable, either by you sometime in the future, or by someone else. Only then you should make it fast, without unnecessarily harming keeping it right. And the best way to do this is to slavishly follow the 3 rules of optimization [3] While there are some who just seem to hate inject, it can, as you point out, be much more intention revealing, which helps in making code right. This is just one of those things, like when and when not to use optional parentheses in Ruby which need a bit of thoughtful reflection, rather than blind adherence to convention. [1] http://c2.com/cgi/wiki?MakeItWorkMakeItRightMakeItFast [2] http://research.microsoft.com/en-us/um/people/blampson/33-hints/webpage.html [3] http://c2.com/cgi/wiki?RulesOfOptimization -- Rick DeNatale Blog: http://talklikeaduck.denhaven2.com/ Twitter: http://twitter.com/RickDeNatale WWR: http://www.workingwithrails.com/person/9021-rick-denatale LinkedIn: http://www.linkedin.com/in/rickdenatale --00163630f2bfb3d612046335a291--