lua-users home
lua-l archive

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


Hi,

Thomas Lauer wrote:
> What's faster: 's:find(...)' or 'string.find(s,...)'?

Here's a benchmark comparing the four ways to get the string length:

$ TIMEFORMAT="%U"
$ time lua -e 'local s=""; for i=1,5e7 do local x=string.len(s) end'
6.77
$ time lua -e 'local s=""; for i=1,5e7 do local x=s:len() end'
5.73
$ time lua -e 'local s,len="",string.len; for i=1,5e7 do local x=len(s) end'
3.96
$ time lua -e 'local s=""; for i=1,5e7 do local x=#s end'
1.01

Lower numbers are better. A dummy loop assigning 0 to x takes 0.68s, so
we arrive at the following timings per operation:

122 ns  string.len(s)
101 ns  s:len()
 66 ns  len(s)
  7 ns  #s

As you can see a builtin operator is the fastest (but not always
available). Then follows the standard practice of caching a library
function, the call via the metatable (requiring one hash lookup plus
some overhead) and the slowest is the uncached use of a library function
(requiring two hash lookups).

So, in your case you should use this:
  local find = string.find
  ... and later use it repeatedly as: find(s,...)

As you can see we are talking about 60 nanoseconds difference per
operation. So you are well advised NOT to optimize this if the
operations are not heavily used inside a loop and/or the time the
operation itself takes is sufficiently longer than this.

Quick summary:
- <10 ns for an internal op, a single loop iteration or similar
- 20 ns for an array lookup
- 30 ns for a hash lookup (global variable or table lookup)
- 40 ns for a metatable hash lookup (1 level)
- 60 ns for a call
- 100-200 ns for a closure or table allocation plus collection

Bye,
     Mike