fundamental tradeoffs in programming
Jan. 17th, 2010 09:55 pmImage you are to write a certain function 'f'. The purpose of calling it is to do X for every element of a list (and optionally Y; this is controlled by a flag)
Which of the following is better?
(a)
(b)
In all languages I know, (a) is more elegant but (b) is more efficient.
In Lisp, another alternative exists: you can write a macro to do a partial evaluation given the value of 'flag'. This is as efficient as (b), but whether it's elegant is debatable. Personally I've never seen an IDE that makes code-rewriting macros nice to work with.
Which of the following is better?
(a)
function f()
for 1:1000
do X
if(flag)
do Y
(b)
function f()
for 1:1000
do X
if(flag)
for 1:1000
do Y
In all languages I know, (a) is more elegant but (b) is more efficient.
In Lisp, another alternative exists: you can write a macro to do a partial evaluation given the value of 'flag'. This is as efficient as (b), but whether it's elegant is debatable. Personally I've never seen an IDE that makes code-rewriting macros nice to work with.
(no subject)
Date: 2010-01-18 06:12 am (UTC)(a) is much more efficient if memory access is expensive;
Actually, I think (a) is better in most cases. Your CPU's branch prediction will probably take care of the "if(flag)" quite nicely.
(no subject)
Date: 2010-01-18 08:57 pm (UTC)(no subject)
Date: 2010-01-19 12:26 am (UTC)if flag then loop x, y
else loop x
I hadn't read Gustavo's version quite right at first; thought his b was my c.
(no subject)
Date: 2010-01-18 06:39 am (UTC)(no subject)
Date: 2010-01-18 07:04 am (UTC)(no subject)
Date: 2010-01-18 01:34 pm (UTC)(no subject)
Date: 2010-01-18 07:12 pm (UTC)(no subject)
Date: 2010-01-18 09:09 pm (UTC)(no subject)
Date: 2010-01-18 10:00 pm (UTC)(no subject)
Date: 2010-01-18 03:34 pm (UTC)(no subject)
Date: 2010-01-18 09:11 pm (UTC)(no subject)
Date: 2010-01-19 02:38 am (UTC)(no subject)
Date: 2010-01-19 07:25 pm (UTC)Maybe this will happen in my lifetime. :-p