Author Topic: Table vs array  (Read 3269 times)

Theremin

  • Full Member
  • ***
  • Posts: 154
  • Karma: +48/-18
  • Worst Server Owner
    • View Profile
    • Visit my YouTube channel
Table vs array
« on: February 10, 2017, 11:45:14 pm »
Which one of these two methods is better and why?
I'm not interested to know which one is better as much as knowing why one is actually better. Keep that in mind before replying


1. Keeping players in an array. Shadow's method

Code: [Select]
playerson <- [];

function onPlayerJoin( player )
{
playerson.push( player.ID );
}

function onPlayerPart( player, reason )
{
playerson.remove( player.ID );
}


2. Keeping players in a table. himselfe's method

Code: [Select]
players <- {};

function onPlayerJoin( player )
{
players.rawset(player.Name,player);
}

function onPlayerPart( player, reason )
{
players.rawdelete(player.Name);
}

Vortrex

  • Full Member
  • ***
  • Posts: 267
  • Karma: +54/-73
    • View Profile
Re: Table vs array
« Reply #1 on: February 10, 2017, 11:59:26 pm »
My method was very similar to himselfe. I just didn't use the rawset or rawdelete methods. Instead I just declared a new table slot on connect, and nulled the slot on part.

Anyway, here's my analysis:
It's not by much, and definitely not noticeable during runtime, but arrays are indexed by an integer while tables are index by a "key" which is usually a string. Iterating through an array is going to be faster than doing so with a table because processing an integer is faster than a string.

However, using the table might be more efficient between the two examples you provided. In the table, you provide a direct reference to the player instance, and can use it without having to use FindPlayer. Again, however, I doubt the performance differences are significant.

But it might be worth noting, that you index the table by player name. I don't recommend this. I would suggest using a player ID. The player name can change during gameplay by either scripting methods or a hack, but the player ID is going to remain the same.

 

© Liberty Unleashed Team.