Regarding 'this' and performance

Hey.
Would it be better to put the “script” in a variable than to use ‘this’? Assuming ‘this’ will be used a couple of times.

Almost certainly irrelevant.
especially if it’s just a “couple of times”
having the extra variable is probably wasted space anyway since you already have a keyword to get ‘this’

1 Like

Alright, thanks for clearing it up :).

Self referencing through a variable (and not ‘this’) is useless.

3 Likes

I just wanted to make sure ‘this’ wasn’t an unnecessary “search”.

1 Like

You don’t need “this” at all, so I’d suggest just not using anything, especially since it doesn’t add any code clarity.

–Eric

1 Like

I thought I had to if I wanted to send the script as an argument for example.

1 Like
otherScript.MySpawnerScript = this // this is necessary

otherScript.MyHealthScript = this.gameObject.GetComponent<Health>(); // this is double redundant
otherScript.MyHealthScript = this.GetComponent<Health>(); // this is still redundant
otherScript.MyHealthScript = GetComponent<Health>(); // works same as the above lines

I was referring to a case where you might want to add a script to a list from within the script itself, like:

aLinkedList.AddLast(this);

I really need to get better at explaining what I mean, sorry.

Curious as to when or why you would need line 2?

I’d say that’s opinion.

It definitely adds clarity for me.

@OP - don’t store it, ‘this’ doesn’t actually access some variable or anything. And you don’t need to put it in, because the compiler implicitly figures it out for you. It is mainly required if the name of something you’re accessing clashes with the name of a local member. ‘this’ will distinguish them. There is no speed difference between using it and not using it.

It’s also used in extension methods.

https://msdn.microsoft.com/en-us/library/dk1507sz.aspx

1 Like

In some cases I prefer to use ‘this’ for clarity too, for example if I want to disable or enable a script, just typing “enabled = false” feels strange to me.
True, I really like using exentsion methods, makes everything more coherent imo.

I like using “this” because it helps with to narrow down the suggestions in the Intellisense when you type “this.” Instead of getting 200 suggestions in the Intellisense, you can get 20.