lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 21 June 2012 10:19, steve donovan <steve.j.donovan@gmail.com> wrote:
> On Thu, Jun 21, 2012 at 9:15 AM, Michal Kottman <k0mpjut0r@gmail.com> wrote:
>> print(("hello world"):sub(7)[3]) --> r
>
> And the point would be, that you can get Lua to do just about anything
> you like, at some performance cost. The sugar s[i] for accessing the
> 'character' at the ith index now slows down all string method lookups.

There is definitely a performance cost. I made a quick
"run-it-ten-million-times-and-measure-how-long-it-takes" benchmark:

local N = 10000000
local str = "hello world"
local s

local start = os.clock()
for i=1,N do
    s = str:sub(7):sub(3,3)
end
print('Standard', os.clock() - start)

getmetatable("").__index = function(s, i)
 if type(i) == "number" then
   return string.sub(s, i, i)
 else
   return string[i]
 end
end

start = os.clock()
for i=1,N do
    s = str:sub(7)[3]
end
print('Modified', os.clock() - start)


The results are as follows for Lua 5.1 on my PC:

$ lua pokus.lua
Standard	2.779684
Modified	7.846075

Note that LuaJIT is able to optimize both cases, so there is no
noticeable difference between the two approaches:

$ luajit pokus.lua
Standard	0.004261
Modified	0.004928