3 ms·
I don't see how this would surprise anyone that has given even the slightest thought to speed optimisation, never mind an "expert". Putting one cheap operation
by robert_tweed 12y ago
I don't see how this would surprise anyone that has given even the slightest thought to speed optimisation, never mind an "expert". Putting one cheap operation into a loop is dominated by the loop overhead, not the cheap operation, so of course two cheap operations with one loop is more efficient than two functions each having their own loop overhead (assuming the loops can't be unrolled of course).
That is never the problem. The problem is that doing this creates tight coupling between the two operations, making it marginally (or sometimes significantly) more expensive when you only need one of them. The coupling also makes your code harder to understand (in all but trivial cases). When the operations are naturally inseparable, this approach makes sense. It also makes sense if you are trying to optimise out a specific problem after profiling.
As a general design, it's usually an anti-pattern and one of the reasons premature optimisation gets such a bad rap with Knuth et al.
Also this case is pretty trivial. There are many cases when trying to couple together multiple operation results in an explosion of edge-cases with unexpected side effects that end up making performance worse, unless you are super careful. This is when "just pick a better algorithm" is usually applicable, except if you tightly couple two algorithms together, it's much harder to swap one out.
- gizmo686 12y agoWith a sufficiently smart compiler, it is possible to get the best of both worlds. If the compiler can prove that the two loops have the same number of iterations, and that the two functions don't interfere with each other, then it can optimize them into one loop. I believe this is one of the tricks Haskell uses.
- kevinnk 12y agoThat's called loop fusion and most optimizing compilers have it. http://en.wikipedia.org/wiki/Loop_fusion http://en.wikipedia.org/wiki/Loop_fusion
- adamnemecek 12y agoI'm guessing that it's a response to the whole "Swift is slower than Obj-C" thing from yesterday https://news.ycombinator.com/item?id=7849213 https://news.ycombinator.com/item?id=7849213 which did exactly this sort of comparison.
- robert_tweed 12y agoOh dear. Microbenchmarks can be misleading at the best of times, but that's a truly awful article. The sad thing is that blog posts like that are easily found on Google by junior-level developers who don't know any better and take all the numbers on faith as representative of the language, even when the methodology is almost certainly complete nonsense.
- adamnemecek 12y agoYeah, judging by https://twitter.com/search?q=http%3A%2F%2Fwww.splasmata.com%2F%3Fp%3D2798 https://twitter.com/search?q=http%3A%2F%2Fwww.splasmata.com%... a lot of people took it at face value.