[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: OO call vs normal call
- From: Mike Pall <mikelu-0705@...>
- Date: Mon, 7 May 2007 15:04:20 +0200
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:
$ time lua -e 'local s=""; for i=1,5e7 do local x=string.len(s) end'
$ time lua -e 'local s=""; for i=1,5e7 do local x=s:len() end'
$ time lua -e 'local s,len="",string.len; for i=1,5e7 do local x=len(s) end'
$ time lua -e 'local s=""; for i=1,5e7 do local x=#s end'
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.
- <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