lua-users home
lua-l archive

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

Doug Rogers wrote:
Again I find myself in agreement with David!

I think this is an honest comparison of how Lua and Java handle the same
algorithm. The algorithm is quite natural and is expressed identically
in both languages.

I disagree. What you call "same algorithm" is actually a naive rewriting of a language idiom into another language. I would call them implementation, instead. OK, doing it this way is "natural", but using string.concat becomes natural to Lua programmers gaining a little experience.

Fortunately, the language shootout allows experienced programmers to improve the implementation in each language, showing the best they can do. And it compares both CPU and memory usage, as often optimizations rely on greater memory use.

If I follow you, I would rewrite Java's loop:

  for (i = 0; i < strBigData.length; i++)


  for (i = 0; i < strlen(strBigData); i++)

in C: it is natural and intuitive.

And very inefficient: in Java, accessing the length of a string is just reading the field of an object, while strlen has to iterate on the string to find its end. Just precomputing this length accelerates dramatically the speed of the C algorithm. Note that in Lua, IIRC, the limits are invariants of the loop, so even an expensive computation is made only once.

Likewise, the "natural" way of doing string concatenation in C is to use strcat (security issues put aside). If I loop on doing strcat of new strings to the big buffer, I have a slow implementation, as strcat do a strlen on the buffer each time. An implementation storing a pointer on the end of the buffer and doing a strcpy instead would be much more efficient.

These are obvious to experienced C programmers, but I saw such code in real products...

Philippe Lhoste
--  (near) Paris -- France
--  --  --  --  --  --  --  --  --  --  --  --  --  --