Lua vs javascript performance

Can Lua be faster than JavaScript in a browser?

I have been working on getting Lua to run in a browser and was asked how much slower it is comparing to JavaScript. I put together two pages — one for Lua and one for JavaScript — to run the equivalent code to measure its performance and got a surprising result: Lua reliably outperformed JavaScript with the following code:

Lua

local canvas = document:getElementById("canvas") canvas.width = canvas.width -- clear the canvas local ctx = canvas:getContext("2d") ctx.fillStyle = "rgb(200,0,0)" ctx:fillRect(130, 130, 50, 50) ctx.fillStyle = "rgba(0, 0, 200, 0.1)" for i = 1, 100 do ctx:fillRect(math.random(0, 300), math.random(0, 300), 50, 50) end

JavaScript

var canvas = document.getElementById("canvas"); canvas.width = canvas.width var ctx = canvas.getContext("2d"); ctx.fillStyle = "rgb(200,0,0)"; ctx.fillRect(130, 130, 50, 50); ctx.fillStyle = "rgba(0, 0, 200, 0.1)"; for (i = 1; i

This clearly wasn’t something I expected as the Lua code compiles down to JavaScript, so it can be running with the same speed (in an ideal case), but clearly should not be running faster (I’ve averaged results over several runs, but you can see for yourself).

Even more puzzling was the fact that each individual part — running a loop with ctx.fillRect(0, 0, 50, 50) or running the same loop with Math.random() call — ran faster with the JavaScript code, but together they ran slower. It took a bit of experimenting, but in the end the mystery was solved: the difference was in Math.random()*300 in JavaScript versus math.random(0, 300) in Lua.

As some of you might have noticed already, math.random(0, 300) call in Lua returns an integer value, whereas Math.random()*300 call in JavaScript returns a float value. I was reading about canvas performance just a day earlier and there was a recommendation to avoid using floating point coordinates as it turns on anti-aliasing, which significantly slows the drawing. That was it; when I added Math.round() call the performance returned to normal.

So, while I was at it, I decided to compare performance of Lua vs. JavaScript on some other calls. The code above was running 50-80% slower in Lua than in JavaScript (with 1000 iterations). A simple loop with one function call — for (i = 1; i — is 3-6 times faster in JavaScript. This is primarily because of table lookup that Lua version has to do. When I changed for i = 1, 10000 do math.abs(-10) end to abs = math.abs; for i = 1, 10000 do abs(-10) end it became only 2-3 times slower than the JavaScript code. Attribute assignment foo.bar had a similar performance: it was 3-6 times slower because of the table lookup and associated function calls in the Lua version.

Читайте также:  Javascript get text file

Overall, I have been very satisfied with the difference in performance and will share the results when I get more complex code running.

Posted by Paul Kulchenko on Tuesday, March 20, 2012 at 2:05 PM

Источник

www.c7i.ru

Производительность: LuaJIT vs Javascript (упоминается и V8)

Производительность: LuaJIT vs Javascript (упоминается и V8)

Сообщение Diatlo » Ср ноя 06, 2013 1:13 pm

«Недавно я написал пост о том как сделать рейтрейсер. Код рейтрейсера тогда был написан на JavaScript. Мне стало интересно, как с этой же задачей справится Lua, а именно LuaJIT 2.0. Ниже результаты сравнения.
Участие принимали Chrome 9.0 Beta, Opera 11.01, Firefox 4.0 Beta 9, Explorer 9 Beta и LuaJIT 2.0 Beta 5. Все пять участников рендерили одну и ту же сцену на экран 1000×1000 по три луча на пиксель»

Результаты следующие (RPS означает «число лучей в секунду»):

Chrome 20,400 RPS
Opera 15,700 RPS
Firefox 9,300 RPS
Explorer 9,000 RPS
LuaJIT 5,000 RPS
Неожиданный результат: LuaJIT оказался самым медленным, причём с отрывом от остальных участников.»

Но всё изменилось, после того, как один из комментаторов чуть поменял код — изменил цикличность сборки мусора:
«Intel Core i5 750, 2.67GHz
Windows 7 Ultimate

chrome9 (9.0.597.84) — 22129
luajit-2.0.0-beta5 — 23946

изменения в коде луа:
понижена цикличность сборки мусора collectgarbage(«setpause», 600)»

«Да, сборка мусора в хроме отменная: скрипт добирается до 200Мб, потом через несколько секунд чистит мусор до 96мб, и снова увеличивается в размере. Насколько я помню, в v8 сборщик многопоточный, видимо тут выигрыш.
С луа все гораздо хуже: если шаг сборки 600, то сборщик видимо вообще не срабатывает, кушая 500мб. Если шаг 300, то потребление памяти медленно растет до 230 мб. «

«Т.е. если функции вызывать глобально, а сборку мусора отложить, то получается быстро?
Ну я так и думал, что в GC дело. От LJ2 следует ожидать, что он сам поднимет загрузку глобалов (load hoisting). На обычных числодробилках даже Crankshaft (V8 после 3.0) к LuaJIT2 вроде не подобрался пока, я уж не говорю о классическом бэкенде (V8 до 3.0).

Насколько я помню, в v8 сборщик многопоточный
Нет, он однопоточный (точнее они, для частичных сборок в молодом поколеннии копирующий scavenger, для полных сборок — MarkSweep/MarkCompact). Ну и пауза в несколько секунд — это, м-м-м-м, не сказать что бы отменный сборщик

Я бы не догадался написать «a = ffi.new(‘double[?]’, . )» вместо «a = <>». Это какая то фича LuaJIT — в документации Lua я такого не встречал. Вообще было бы неплохо, если бы Mike написал подобные простые сценарии кода.
Да, это фича LuaJIT 2, начиная с beta6. См. luajit.org/ext_ffi.html и соседние топики в меню слева.
FFI Library: The FFI library allows calling external C functions and using C data structures from pure Lua code. Использование структур С из Луа.

К сожалению, не приводятся результаты после замены луа-таблицы <> на ffi C-массив с элементами типа double. Судя по-всему, там всё зашкаливает =)))))).

Источник

Is JS faster than Lua?

Lua is also good in performance than any languages but it is not that faster say for a simple loop with one function call which executes on runs slower when compared to Javascript. But Lua can be made faster which is known as further improvement in Lua by using the LuaJIT compiler which speeds the rival codes.

Читайте также:  Python grad to rad

Is Lua faster than node JS?

If you’re comparing to Lua proper, V8 (the JavaScript engine in Node. js) is faster. The main distribution of Lua has no JIT compiler. It’s strictly interpreted.

Is Lua the fastest language?

Several benchmarks show Lua as the fastest language in the realm of interpreted scripting languages. Lua is fast not only in fine-tuned benchmark programs, but in real life too. Substantial fractions of large applications have been written in Lua.

Is JavaScript the fastest language?

js one of the fastest programming languages today. Node. js compiles fast also because it runs on Google’s V8 JavaScript engine that compiles the code into native machine instructions to make it run fast.

Is Lua faster than Julia?

When I write out the same code for finding the smallest possible multiple of a number, Julia is much faster than Lua, both taking ~3 seconds & ~23 seconds respectively.

Why Javascript is 100x Faster than Python

Is Lua outdated?

While Lua is still used fairly often in gaming and web service, it performed poorly in terms of community engagement and job market prospects. That being said, in spite of its age, Lua’s growth has flat-lined rather than declined, which means that although it’s not popular, it’s not dying either.

Is Roblox just Lua?

Code in Roblox is written in a language called Lua, and it’s stored and run from scripts. You can put scripts in various containers in the Explorer. If you put a script under a Part, Roblox will run the code in the script when the part is loaded into the game.

Why is js so fast?

js is so fast. Node. js is single-threaded and asynchronous: this means that all I/O activity does not interfere with other processes, and it is possible to send emails, read and write files, query databases, and so on, all at the same time. Each request to the web server does not have a different Node.

Is JavaScript dead language?

JavaScript Is The Only Viable Option For Front-End Web Development. The main reason that JavaScript has never died, and likely will not die anytime soon, is because it’s the best option we have for frontend development. There have been a lot of technologies that have done their best to replace JavaScript.

What is the fastest coding language?

C++ is the fastest programming language. It is a compiled language with a broad variety of applications that is simple to learn. C++ was the clear winner, with Java and Python coming in second and third, respectively.

What is Lua closest to?

Lua is similar to Python in that it is an open-source programming language that is constructed on top of the C computer language. It is a lightweight programming language that is also capable of being extended.

Читайте также:  Реализация пользовательского интерфейса java

Why is Lua so small?

Lua was built for portability and is designed to have a small foot print. The standard library is small and has clean interfaces. Lua does not include a Regex library since: Unlike several other scripting languages, Lua does not use POSIX regular expressions (regexp) for pattern matching.

Why do games use Lua?

In video game development, Lua is widely used as a scripting language by game programmers, perhaps due to its perceived easiness to embed, fast execution, and short learning curve. In 2003, a poll conducted by GameDev.net showed Lua as the most popular scripting language for game programming.

What is Lua best for?

Lua is a scripting language used for procedural programming, functional programming, and even object-oriented programming. It uses a C-like syntax, but is dynamically typed, features automatic memory management and garbage collection, and runs by interpreting bytecode with a register-based virtual machine.

How fast is Lua programming?

What is harder Lua or Python?

Lua is easier than the Python language but Python is popular and demanding language than the Lua language for beginners. Python is a scripting language but it is heavy and slower than the Lua language but Lua is a light-weight, portable, and rapid execution language.

Is JavaScript a hated language?

Why avoid JavaScript?

It blocks several elements on websites that include tracking cookies, thus enhancing your privacy. Disabling JavaScript can break websites too, affecting the user experience.

Is web development dying 2023?

Web development is currently an excellent career to have. The demand is already there for web developers and the projections look great. Demand for the next decade is expected to steadily grow, and the industry is considered quite lucrative.

Is js faster than C++?

For one, once the code is compiled, C++ is much faster than JavaScript, often more than ten times faster.

Is js as fast as Python?

Depending on your project plans, both languages offer different solutions whether it’s a single page web app, or a data processing and metrics visualization project. A generalized comparison of JavaScript vs Python shows JavaScript’s faster speed in production, but Python’s simplicity.

Is js faster than Python?

js has a faster performance thanks to its advanced multithreading ability. Unlike Python, which has to process requests in a single flow. On the one hand, applications that require dynamic and real-time interactions are often built on JavaScript to avoid making users wait.

Is GTA written in Lua?

So, in summary, while the engine that GTA V runs on it indeed written in C/C++, Lua can easily be included over the top of it as an embedded language for modders to use.

Can a 12 year old learn Roblox Lua?

With its proprietary web-based drag-and-drop code editor, kids age 8+ can learn how to develop their own games using Roblox Studio and the Lua programming language.

Is Lua coding hard?

Compared to other programming languages, Lua is not too difficult to learn. Many students are able to start embedding it into their applications after only a small amount of instruction. Because Lua is such a popular and relatively easy language, there are various ways for students to learn it.

Источник

Оцените статью