Lua vs JavaScript

TL;DR: Which one has better performance? Lua or JavaScript? (test scripts I used can be seen below)

====================================================

So, I am scripting in Lua, but someone suggested that Lua runs slower than JavaScript.
Now, obviously I wanted to make some research about this, but I found nothing on the internet / forums, so I created two scripts, one in Lua, one in JavaScript and I made them identical (as much as the languages allowed it), but both scripts achieve the same results.
After running both codes after each other, the results were interesting.
Picture of the results:


As you can see, JavaScript was significantly slower.

.js script:

RegisterCommand("jsC", () => {
    let counter = 0;
    let startTime = GetNetworkTimeAccurate();
    console.log(`startTime: ${startTime}`);

    for (let j = 0; j <= 100; j++) {
        for (let i = 0; i <= 10000; i++) {
            let playerPed = PlayerPedId();
            let [playerX, playerY, playerZ] = GetEntityCoords(playerPed);
            let vdist = Vdist(playerX, playerY, playerZ, 0, 0, 0);
            if (!playerPed)
                counter = 0;
            if (vdist > 0)
                counter++;
        }
    }

    console.log(`counter: ${counter}`);
    let endTime = GetNetworkTimeAccurate();
    console.log(`endTime: ${endTime}`);

    console.log(`runTime: ${endTime - startTime} ms.`);
})

.lua script:

RegisterCommand("luaC", function()
	local counter = 0
	local startTime = GetNetworkTimeAccurate()
	print("startTime: " .. startTime)

	for j = 0, 100 do
		for i = 0, 10000 do
			local playerPed = PlayerPedId()
			local pos = GetEntityCoords(playerPed)
			local vdist = Vdist(pos, vector3(0, 0, 0))
			if not playerPed then
				counter = 0
			end
			if vdist > 1 then
				counter = counter + 1
			end
		end
	end

	print("counter: " .. counter)
	local endTime = GetNetworkTimeAccurate()
	print("endTime: " .. endTime)

	print("runtime: " .. (endTime - startTime) .. " ms.")
end)

I ran these commands multiple times, after each other, the same command 10 times, but the results were the same.
Is there anything I did wrong, or my results are correct? (So JavaScript is that much slower?)

3 Likes

I have no idea which one is faster, I haven’t done any tests myself so don’t take my word for it. But according to a Cfx element “an equivalent busy-loop in JavaScript is about 15% slower”.

There’s also some old “benchmark” tests provided by a community member that has been around for quite some time. They’re however over one years old so I’m not sure how relevant those are. I’m also not sure how it’s been tested but here they are:

2 Likes

That is interesting, thank you for sharing all that info and the spreadsheet.
The spreadsheet shows an even bigger difference between Lua and JavaScript, so maybe they optimized it since, but it is still not as good as Lua and it also proves that even if my script isn’t the best to measure the performance, it is not completely wrong.

the JS example you provided is particularly nasty and shows a bit larger deviation as it uses the V8 array API a lot for vector return values, and the V8 C++ API is very, very unoptimized.

however, native calls aren’t the only operation done in scripts, e.g. Lua tables are going to give you a bad time compared to other languages

2 Likes

Thank you for clarifying!

I was suspecting that my code isn’t going to represent the whole story behind it, that would be too easy. :slight_smile:

Ive been questioning myself about this, as a software developer I felt the need to use Javascript instead of Lua in most cases.

The different running times are a factor to take into consideration, but there are a few more things that you should consider.

First, think about the complexity of your project. Both languages are better in different cases:

  • Lua (Small/Medium Projects)
  • Javascript (Small/Medium/Large Complex Projects)

Indeed Lua runs faster with small scripts, but in large projects with a need to have organized and structured data, Javascript will run faster just because it has a better way of handling objects and creating modular instances.

For example, if you are coding a gamemode you probably want to use Javascript.
But there are exceptions, take a look at this toggle-minimap event script:

Javascript

on('toggle-minimap', () => console.log("this is a test"))

Lua

AddEventHandler('toggle-minimap', function()
    print("this is a test")
end

They are not so different here, right?


Now lets see how it looks like when we create a control listener instead of an event.

Javascript

setTick(() => IsControlJustReleased(0, 243) && console.log("this is a test"))

Lua

CreateThread(function()
    while true do
        Wait(0)
        if IsControlJustReleased(0, 243) then
           print("this is a test")
        end
    end
end)

Now we can start to see some differences between them.


Lets take a look at object handling in both languages:

Javascript

const arr = [
    {key: "1", value: 1},
    {key: "2", value: 2},
    {key: "3", value: 3},
]

for(const { key, value } of arr){
    console.log(key, value)
}

Lua

local arr = {
    {key = "1", value = 1},
    {key = "2", value = 2},
    {key = "3", value = 3},
}

for i, obj in ipairs(arr) do
    print(obj.key .. " " .. tostring(obj.value))
end

In large projects, the way you structure and access your data will be one of the most important things to consider.


Now, lets see how both languages create classes.

Javascript

class Account {
    constructor(balance){
        this.balance = balance
    }

    withdraw(amount){
        this.balance = this.balance - amount
    }
}
const acc = new Account(1000)
acc.withdraw(100)

Lua

Account = {}
Account.__index = Account

function Account:create(balance)
   local acnt = {}             
   setmetatable(acnt,Account)  
   acnt.balance = balance     
   return acnt
end

function Account:withdraw(amount)
   self.balance = self.balance - amount
end
local acc = Account:create(1000)
acc:withdraw(100)

I think you can clearly see the differences between Javascript and Lua, so based on that you should decide what works best for you.

I think both languages have their use cases depending on what you need.

5 Likes