[erlang-questions] foldl vs foldr and ++

Richard O'Keefe ok@REDACTED
Fri May 11 04:02:41 CEST 2012

On 11/05/2012, at 7:30 AM, Robert Virding wrote:

> These say more about it:
> http://www.erlang.org/doc/efficiency_guide/myths.html#tail_recursive

Four key points from that:
the relative costs of tail and body recursion have *changed*,
they are *different* on different machines,
don't assume but measure, and
you should probably do whatever is easiest to get your
program working correctly rather than micro-optimising.

I was just looking at some student Java code where he'd
read a line of code as a String,
reversed it so he could process it from right to left,
and reversed it again for printing.
Since there is no String.reverse() -- yet -- in Java,
he had written something like this:

	StringBuilder b = new StringBuilder(s.length());
	for (int i = 0; i < s.length(); i++)
	    b = b.append(s.substring(i, 1).toCharArray()[0]);
	return b.toString();

This can be written more efficiently, but it's best of all
just not to reverse the string in the first place.  Keep
the code at a level where you can see what's going on well
enough to spot the really _big_ efficiency gains.

More information about the erlang-questions mailing list