[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: optimization improves code readability
- From: Leo Razoumov <slonik.az@...>
- Date: Fri, 23 Jan 2009 06:40:01 -0500 (EST)
On Thu, 22 Jan 2009, David Manura wrote:
Date: Thu, 22 Jan 2009 07:37:20 -0500 (EST)
From: Leo Razoumov
In Lua, on the other hand, some
optimizations make code *MORE* readable.
Here's one optimization that is less readable:
local y = myvar^4 / (1 + myvar^2)
local x2 = myvar*myvar
local y = x2*x2 / (1 + x2)
-- Lua itself couldn't do this factorization due to
-- the possibility not only of overflow but also
-- metamethods, except in special cases if detected
-- by code analysis
The optimization above is, in essence, an *algorithmic* optimization
rather than a programming optimization.
You are defining your own way of raising number to some power
relying upon associativity of multiplication.
In a finite precision math, such optimization could lead to
non-bit-exact results when compared with an unoptimized case.
I really do not want my compiler to do such things for me behind the scenes.
By the same token the following function
function mysum1(x)
assert(math.abs(x)<1)
local sum=1
for i=1,9999 do
sum= sum + x^i
end
return sum
end
can be "optimized" into
function mysum2(x)
assert(math.abs(x)<1)
return 1/(1-x)
end
x= 0.5
print(mysum1(x), mysum2(x), mysum1(x) - mysum2(x))
assert(mysum1(x) == mysum2(x))
--Leo--