At the moment, in the Lua support extension we have been developing,
wikitext is output to the wiki via the return value of a function. For
example in wikitext you would have:

{{#invoke:MyModule|myFunction}}

Then in [[Module:MyModule]]:

local p = {}
function p.myFunction()
   return 'Hello, world!'
end
return p

This is all nice and elegant and will work. There is an alternative
convention commonly used in scripting languages (and programming in
general for that matter), using a print function:

local p = {}
function p.myFunction()
   print('Hello, world!')
end
return p

I would have been happy to leave it as Victor Vasiliev made it, i.e.
using return values, but I happened across a performance edge case in
Lua which made me think about it. Specifically, this:

function foo(n)
   s = ''
   for i = 1, n do
       s = s .. toString(i)
   end
   return s
end

has O(n^2) running time. For 100,000 iterations it takes 5 seconds on
my laptop. Apparently this is because strings are immutable, so the
accumulator needs to be copied for each concatenation. It's very
similar to the situation in Java, where a StringBuffer needs to be
used in such an algorithm.

It's easy enough to work around, but the problem is obscure enough
that I think probably most of our users will not realise they need to
work around it until it becomes severe.

It would be possible to provide a print() function which does not
suffer from this problem, i.e.

function foo(n)
   for i = 1, n do
       print(i)
   end
end

could run in O(n log(n)) time. Intuitively, I would expect that
providing such a print function would encourage a programming style
which would avoid at least some instances of repetitive concatenation.

The performance issue is probably no big deal, since most templates
are probably not going to be concatenating hundreds of thousands of
strings, and 5 seconds is still quicker than the time it takes most of
our featured articles to render at the moment. But like I say, it got
me thinking about it.

Does anyone have any thoughts on return versus print generally? Are
there other reasons we would choose one over the other?

-- Tim Starling


_______________________________________________
Wikitech-l mailing list
Wikitech-l@lists.wikimedia.org
https://lists.wikimedia.org/mailman/listinfo/wikitech-l

Reply via email to