Declaring variables for better readability of the code

Status
Not open for further replies.

Eliaquim

Raze: The Rakuen Zero's Guardian!
Veteran
Joined
May 22, 2018
Messages
901
Reaction score
358
First Language
Portuguese - Br
Primarily Uses
RMMV
Hi people! :D

Well, it's me again with another doubt...

In my plugin I have a lot of this:

Code:
SceneManager._scene._helpWindow;
SceneManager._scene._categoryWindow.currentSymbol();
Eli.Param.HelpWindows.menuText;
Eli.Param.HelpWindows.etc;
So, to keep the lines short, I have assigned these codes to variables, inside the scope of the function:

Code:
function myFunction() {
const thisHelp = SceneManager._scene._helpWindow;
const thisSymbol = SceneManager._scene._categoryWindow.currentSymbol();
const thisText = Eli.Param.HelpWindows.menuText
thisHelp.x = 100;
};

function myFuntion2() {
const thisHelp = SceneManager._scene._helpWindow;
const thisSymbol = SceneManager._scene._categoryWindow.currentSymbol();
const thisText = Eli.Param.HelpWindows.etc;
thisHelp.x = 100;
}
But the case is, that I have a lot of functions.
My lines get short. But in return, I add many lines to the code.

With that, I came to thinking...

Question 1 - Declaring those variables inside of the scope of the functions, many times like in the example above, can cause me a performance issue?


What is best to do:

Option A - Declare those variables one time, outside the function. And then, only change its value inside the function.
Code:
let thisHelp = null;
let thisSymbol = null;
let thisText = null;

function myFunction() {
thisHelp = SceneManager._scene._helpWindow;
thisSymbol = SceneManager._scene._categoryWindow.currentSymbol();
thisText = Eli.Param.HelpWindows.menuText
thisHelp.x = 100;
};

function myFuntion2() {
thisHelp = SceneManager._scene._helpWindow;
thisSymbol = SceneManager._scene._categoryWindow.currentSymbol();
thisText = Eli.Param.HelpWindows.etc;
thisHelp.x = 100;
};

Option B - Don't use the variables. Instead, use the code itself inside the function:
Code:
function myFunction() {
SceneManager._scene._helpWindow.x
SceneManager._scene._helpWindow.setText(Eli.Param.HelpWindows.etc)
}

function myFunction2() {
SceneManager._scene._helpWindow.x
SceneManager._scene._helpWindow.setText(Eli.Param.HelpWindows.etc)
}

Option C - Do the plugin like in the firsts example, declaring variables inside each function.
Code:
function myFunction() {
const thisHelp = SceneManager._scene._helpWindow;
const thisSymbol = SceneManager._scene._categoryWindow.currentSymbol();
const thisText = Eli.Param.HelpWindows.menuText
thisHelp.x = 100;
};

function myFuntion2() {
const thisHelp = SceneManager._scene._helpWindow;
const thisSymbol = SceneManager._scene._categoryWindow.currentSymbol();
const thisText = Eli.Param.HelpWindows.etc;
thisHelp.x = 100;
}



Or I'm worrying too much about all of this. And the way that I do that doesn't matter to javascript, in terms of performance?

Question 2 -
Declaring variables with LET keyword outside of functions will allow other plugins to modify or have access to those variables (if they use variables with the same name)?
 

Another Fen

Veteran
Veteran
Joined
Jan 23, 2013
Messages
536
Reaction score
249
First Language
German
Primarily Uses
I'm still quite new to Javascript and not an expert in software development, so I might be wrong with the details here...

1) Usually local variables are stored in a pre-occupied memory block (stack) and declaring more local variables would only increase the amount of stack the function call would reserve for itself. This may decrease the amount of nested function calls you can do before the stack overflows (which usually should not happen anyways unless you are doing some deep recursion) but should not affect performance in any way.

Also your code will likely get translated into a more system-oriented language including some optimization, so I wouldn't be surprised if B and C would end up very similar anyways.

But overall I think you probably do worry about this too much.
Things like reading or writing variables are basic operations and very fast, and while it's definitely a good thing trying to keep your code performant, you would have to save a lot of these to have any impact. Making your code easy to read should be the priority here.
If your code is running poorly, it is usually more efficient to look at the macro level and see if you can change something in the working process to improve performance.

2) I might be wrong here, but I'd expect other plugins to share these variables.
However, you can limit the scope of your variables to your plugin by wrapping your code inside another function and executing it:
Code:
(function() {
    let a;
    let b;
    ...
})();
 
Last edited:

TWings

The Dragon Whisperer
Veteran
Joined
Jul 26, 2017
Messages
375
Reaction score
637
First Language
French
Primarily Uses
RMMV
You need to keep in mind that assigning values will actually copy that value, whereas assigning objects will just add a new pointer to that object. So those are 2 really different situations.
 

CaRa_CrAzY

Undefined Custom Title
Veteran
Joined
Jan 19, 2019
Messages
42
Reaction score
19
First Language
Portuguese
Primarily Uses
Other
Well... here are my 2 cents on the issue.

About question 1:
If I have not misunderstood it, you are worried about those deep nested variables inside other functions and objects, right?

I wouldn't say you are worrying too much about this since it's very important that you start to see issues in the code you write, however in terms of performance, which is your first concern, it doesn't matter so much unless dealing with very heavy objects. This kind of micro-optimization does more harm than good.

You should focus more on readability and maintainability.
If declaring the variables in an outer function turns it more readable, you should consider doing it.
However, in a maintainability standpoint, you weren't supposed to need all those long access chains to reach the variables you need. Perhaps you could create intermediate objects holding those information and access these information through these objects.

About question 2:
I am not very experienced with javascript regarding MV, so I expect that more the experienced users correct me if I am wrong.

But, yes. If you declare a variable outside the outermost function of your plugin, they can access and modify the values of these variables. However, if they use variables with the same name, and one of them are declared as let, an error will occur. This won't happen if both are declared as var. I think that's why it is advised to use let over var.
If you use const plugins will only be able to access the value, but not modify it. This is also valid to your own plugin.

So if you want to prevent other plugins to access your variables you should consider an IIFE, like @Another Fen suggested.
 

Eliaquim

Raze: The Rakuen Zero's Guardian!
Veteran
Joined
May 22, 2018
Messages
901
Reaction score
358
First Language
Portuguese - Br
Primarily Uses
RMMV
@Another Fen @TWings thanks for sharing your thoughts!
I don't like to use IIFE ^^''

@CaRa_CrAzY When you say objects, you mean something like this:
Code:
Eli.Param.HelpWindows.myObjects = {
thisHelp: SceneManager._scene._helpWindow,
thisSymbol: SceneManager._scene._categoryWindow.currentSymbol(),
thisText: Eli.Param.HelpWindows.menuText
}
Then access these objects like this?

Code:
Eli.Param.HelpWindows.myObjects.thisHelp.x
 

CaRa_CrAzY

Undefined Custom Title
Veteran
Joined
Jan 19, 2019
Messages
42
Reaction score
19
First Language
Portuguese
Primarily Uses
Other
I was thinking in something more or less like this:

Code:
function someRandomWindow(helpWindow, currentSymbol, menuText, etc) {
   
    function myFunction() {
        helpWindow.x = 100;
    }
   
    function myFunction2() {
        helpWindow.x = 200;
    }
   
    function myFunction3() {
        helpWindow.x = 300;
    }
   
}

myWindow = new someRandomWindow(
    SceneManager._scene._helpWindow,
    SceneManager._scene._categoryWindow.currentSymbol(),
    Eli.Param.HelpWindows.menuText,
    Eli.Param.HelpWindows.etc,
)

myWindow.myFunction();
myWindow.myFunction2();
myWindow.myFunction3();
How you are really going to do it depends on what are you doing.
 

MrNybbles

Veteran
Veteran
Joined
Nov 6, 2019
Messages
59
Reaction score
31
First Language
English
Primarily Uses
RMMV
Question 1 - Declaring those variables inside of the scope of the functions, many times like in the example above, can cause me a performance issue?
No. If you create an object that is destroyed when you leave the function vs explicitly storing the object creates negligible overhead because otherwise it is stored in an implicit temporary location (otherwise you couldn't call a method or access a property). All you are doing with let and const is creating explicit references to the objects.

Example A differs from B and C because in example A you are essentially creating global variables*.
Only use global variables if the contents are shared between multiple functions, otherwise the stored object may never be garbage collected. This is exactly the sort of thing you are asking about to avoid.

The differences behind the ideas of B and C on performance are negligible so do what works best for you.

While many of us still put code inside of an IIFE, modern JavaScript allows using braces to create scope where let and const variables will have local scope and be garbage collected after leaving the scope. The braces method of creating scope has less overhead than creating an IIFE, but this isn't a big difference.

Code:
(function(){
  const date = new Date();
})();

{ // Same as above, but without the IIFE
  const date = new Date();
}

Minimizing the amount of garbage you create is probably what will help you the most.
Code:
  const time = new Date().getTime(); // Creates an object to call a method. This new object becomes unnecessary garbage.
  const time = Date.now(); // Calls a static method, thus creates less garbage.
Also, better code isn't always about performance but about algorithms. For example, plugins that rely on the game running at 60 fps will have more problems (especially when another plug-in unlocks the framerate) than if you use Date.now() each frame to get the difference in time, then use an integration function to find where the object currently is. Gaffer has good articles on this sort of stuff (although you probably won't worry about multiplayer sync issues so using a timestep isn't necessary it will fix a lot of collision problems if you have objects moving really fast).

https://gafferongames.com/post/integration_basics/

Question 2 - Declaring variables with LET keyword outside of functions will allow other plugins to modify or have access to those variables (if they use variables with the same name)?
Yes. JavaScript has changed over time, but now you can use let and const at the root level to create global variables*.


* Technically there are no global variables. They are properties of the global object which is why they behave like properties of other objects.
 

Eliaquim

Raze: The Rakuen Zero's Guardian!
Veteran
Joined
May 22, 2018
Messages
901
Reaction score
358
First Language
Portuguese - Br
Primarily Uses
RMMV
@MrNybbles interesting explanation!
So, If I understand you correctly, there is a difference between the three options(A, B, C), but is negligible. However, the best answer to my question is that I can continue to declare LET and CONST inside the functions, as local variables. Because those local variables, will be destroyed after executing the function, so it will not "occupy" or "flood" the performance of the code.
And only create global variables, for the contents that multiple functions will need to access. Right?
 

MrNybbles

Veteran
Veteran
Joined
Nov 6, 2019
Messages
59
Reaction score
31
First Language
English
Primarily Uses
RMMV
So, If I understand you correctly, there is a difference between the three options(A, B, C), but is negligible.
The difference between B and C is negligible because the implicit/explicit referencing variable will let go of the object. A is the one you want to avoid (unless you really want to keep that object for the life of the program).

However, the best answer to my question is that I can continue to declare LET and CONST inside the functions, as local variables. Because those local variables, will be destroyed after executing the function, so it will not "occupy" or "flood" the performance of the code.
Yes, you got it!

And only create global variables, for the contents that multiple functions will need to access. Right?
This is a bit more complicated, but in general yes.

Exceptions do exist. For example, if you have something like a large database (e.g. $dataAnimations) then keeping this in a global variable will save you from loading it over and over again (and loading something large takes time). The ImageCache is the same idea of caching large or frequently-used objects.
 

Eliaquim

Raze: The Rakuen Zero's Guardian!
Veteran
Joined
May 22, 2018
Messages
901
Reaction score
358
First Language
Portuguese - Br
Primarily Uses
RMMV
@MrNybbles ok, thank you!
You know, I was searching in google for something like: "javascript, performance, variables" etc. And never found anything related to what I want.
Now my search is "javascript garbage collection" and this helps me so much to understand how js handle memory. I think a change in the keyword led me to the information I really wanted! ^^
 

bgillisp

Global Moderators
Global Mod
Joined
Jul 2, 2014
Messages
12,503
Reaction score
12,792
First Language
English
Primarily Uses
RMVXA

This thread is being closed, due to being solved. If for some reason you would like this thread re-opened, please report this post and leave a message why. Thank you.

 
Status
Not open for further replies.

Users Who Are Viewing This Thread (Users: 0, Guests: 1)

Latest Threads

Latest Posts

Latest Profile Posts

Why is it that every time I take a short break from here, we get a new moderator?
Stream will be going live early today as I will be working on some music before I transition to art! When I switch to art, I will be focusing on making a new stream avatar~ Feel free to drop by!
For anyone who has uploaded a game to Steam and wonders if they actually check your game's build when you first upload it, I can personally vouch for Steam.
6 more towns to make in my game. SIX. not done with interiors yet but SIX EXTERIORS.
what to do when you come across a person that has stated "What if I say, f*** their EULA? I could probably get away with it." concerning asset packs sold here... on this site ...

Forum statistics

Threads
93,497
Messages
913,022
Members
123,033
Latest member
LageCL
Top