lua-users home
lua-l archive

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

Miles Bader wrote:
> Mike Pall <> writes:
> > No, please don't do this. The namespace lookup will be shortcut,
> > so there's no need (and in fact it's counter-productive) to keep
> > local references to functions. Also, please don't keep local
> > references to intermediate parts of nested arrays/structs (always
> > use 'y = foo[10].x' and not: 'local s = foo[10]; ...; y = s.x')
> Why is it counter-productive?  _Not_ being able to do this will be very
> counter-intuitive for most programmers I think...

Err, no. Please read again. You _can_ do this, of course. But it's
not helpful to create intermediate pointers/refs where a single
expression would suffice.

Neither is it a good idea to do this with any modern C compiler.
The general rule is _not_ to create pointers where you can use
indexes, because the compiler (whether C or LuaJIT) has to work
hard to undo your manual 'optimization' (which really isn't one).

So if you have this struct of arrays:

  struct foo { int x[100], y[100], z[100]; };
  local s ="struct foo")

... and want to copy two components, then do it like this:

  for i=0,99 do s.x[i] = s.y[i] end -- Good!

... and NOT like this:

  local x, y = s.x, s.y -- Creates two intermediate references.
  for i=0,99 do x[i] = y[i] end   -- Works, but please don't!

In LuaJIT's case, intermediate references are always created in
the interpreter, but the JIT compiler can easily eliminate them if
they are consumed right away. This doesn't work if you store them
in some local variable and this variable escapes to some side
exit. Then it gets really difficult or impossible to eliminate the
allocation of the intermediate reference (and allocation sinking
is not yet implemented, too).

A C compiler easily gets into trouble with pointer aliasing and
needs some expensive analysis to turn this back into the original
index expression the programmer tried to 'optimize'. :-)

Morale: what a programmer may think is helpful for the compiler,
often is not. So write things in the most straightforward way.