# Automatic Optimizations (Free Editor Code)

**URL:** https://discussions.unity.com/t/automatic-optimizations-free-editor-code/655679
**Category:** Performance & Profiling
**Tags:** Scripting
**Created:** [February 17, 2017, 3:25am UTC](https://discussions.unity.com/t/automatic-optimizations-free-editor-code/655679 "2017-02-17T03:25:08Z")
**Posts on this page:** 20
**Page:** 1

<div class="post-metadata">

### Author: ![image28\_1](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/image28_1/32/293546_2.png) [@image28\_1](https://discussions.unity.com/u/image28_1)
#### Post date: [February 17, 2017, 3:25am UTC](https://discussions.unity.com/t/automatic-optimizations-free-editor-code/655679/1 "2017-02-17T03:25:08Z")

</div>

Wrote some scripts to auto optimize code, would like it if some people tested them out, just don’t get mad if they break your code a bit ( backup first ). Place all files in the editor folder. Plan to turn them into a store asset once I develop and test them a bit more.

First one replaces string in update function with hardcoded string set in start to remove garbage collection

header.txt

```auto
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class stringManager : MonoBehaviour
{
     private static stringManager instance = null;
 
     // Game Instance Singleton
     public static stringManager Instance
     {
         get
         {
             return instance;
         }
     }
 
     private void Awake()
     {
         // if the singleton hasn't been initialized yet
         if (instance != null && instance != this)
         {
             Destroy(this.gameObject);
         }
         instance = this;
         DontDestroyOnLoad( this.gameObject );
     }

     // Strings DB ( Reduces Garbage Collection )

```

footer.txt

```auto
}

```

stringOptimizer.cs

```auto
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.IO;
using UnityEngine;
using UnityEditor;

public class stringOptimizer
{

    private static StreamWriter managerOutput;
    private static string line;
    private static int bracketCount;
    private static bool bracketRead = false;

    [MenuItem ("Window/Optimize/Optimize Strings", false)]
    static void FindAssetsUsingSearchFilter ()
    {
        // Find all code assets
        string[] guids = AssetDatabase.FindAssets ("t:MonoScript");
        bool inUpdate;
        bool inFixedUpdate;
        bool inLateUpdate;

        if (File.Exists ("Assets/stringManager.cs")) {
            File.Copy ("Assets/stringManager.cs", "Assets/stringManager.cs" + ".undo");
        }
        managerOutput = new StreamWriter ("Assets/stringManager.cs");

        stringManagerHeadFoot ("Assets/Editor/header.txt");

        Debug.LogError (guids.Length + " Strings found");
        foreach (string guid in guids) {
            int stringCount = 0;

            Debug.Log (AssetDatabase.GUIDToAssetPath (guid));
            if (!AssetDatabase.GUIDToAssetPath (guid).Contains ("Editor")) {
                saveUndoFile (AssetDatabase.GUIDToAssetPath (guid));
                StreamReader input = new StreamReader (AssetDatabase.GUIDToAssetPath (guid));
                StreamWriter output = new StreamWriter ("Assets/temp.txt");
                bracketCount = 0;
                inUpdate = false;
                inLateUpdate = false;
                inFixedUpdate = false;

                while ((line = input.ReadLine ()) != null) {
                    Debug.LogError ("Read line " + line);

                    bracketRead = false;

                    inUpdate = inFunction ("Update(", "Update (", inUpdate, 0);
                    inLateUpdate = inFunction ("LateUpdate(", "LateUpdate (", inUpdate, 0);
                    inFixedUpdate = inFunction ("FixedUpdate(", "FixedUpdate (", inUpdate, 0);

                    if (((inUpdate) || (inFixedUpdate) || (inLateUpdate)) && (line.Contains ("\"") && (!line.Contains ("case") && (!line.Contains ("[ContextMenu"))))) {

                        line = line.Replace ("\\\"", "DOUBLESTRING");
                        Debug.LogError ("String found");
                        string[] temp = line.Split ('"');
                        if (temp.Length >= 3) {
                            Debug.LogError (temp [0] + temp [1] + temp [2]);

                            int count = 1;
                            while (count < temp.Length) {
                            
    
                                Debug.LogError ("String number " + count);
            
                                Debug.LogError ("Match");
                                // write string to string manager
                                managerOutput.Write ("\tpublic string " + Path.GetFileNameWithoutExtension (AssetDatabase.GUIDToAssetPath (guid)) + stringCount + " = \"" + temp [count] + "\";");
                                managerOutput.WriteLine ();
                                // replace string with stringManager.Instance.classnameStringcount
                                string originalString = '"' + temp [count] + '"';
                                string replaceString = "stringManager.Instance." + Path.GetFileNameWithoutExtension (AssetDatabase.GUIDToAssetPath (guid)) + stringCount;
            
                                line = line.Replace (originalString, replaceString);

                                //line.Replace (originalString, replaceString);
                                Debug.LogError ("Writing line " + line + " replaced " + originalString + " with " + replaceString);
                                
                                stringCount++;
                        

                                count = count + 2;
                            }
                        }

                        line = line.Replace ("DOUBLESTRING", "\\\"");
                    }

                    // Write the current line
                    output.Write (line);
                    output.WriteLine ();
                }

                output.Close ();
                input.Close ();

                File.Delete (AssetDatabase.GUIDToAssetPath (guid));
                File.Move ("Assets/temp.txt", AssetDatabase.GUIDToAssetPath (guid));
            }

        }

        stringManagerHeadFoot ("Assets/Editor/footer.txt");
        managerOutput.Close ();
    }

    static void stringManagerHeadFoot (string headerPath)
    {
        string headerLine;
        StreamReader input = new StreamReader (headerPath);

        while ((headerLine = input.ReadLine ()) != null) {
            managerOutput.Write (headerLine);
            managerOutput.WriteLine ();

        }

        input.Close ();
    }

    static bool inFunction (string search1, string search2, bool testCondition, int braceMatch)
    {
        if ((line.Contains (search1)) || (line.Contains (search2))) {
            testCondition = true;
            if ((line.Contains ("{")) && (!bracketRead)) {
                bracketRead = true;
                bracketCount++;
            }
            Debug.LogError ("In Function " + search1);
            Debug.LogError (bracketCount);
        } else {

            if (testCondition) {
                if ((line.Contains ("{")) && (!bracketRead)) {
                    bracketRead = true;
                    bracketCount++;
                    Debug.LogError ("Open function " + bracketCount);
                }

                if ((line.Contains ("}")) && (!bracketRead)) {
                    bracketRead = true;
                    bracketCount--;
                    Debug.LogError ("Close function " + bracketCount);
                }

                if ((bracketCount == braceMatch)) {
                    testCondition = false;
                    Debug.LogError (bracketCount);
                    Debug.LogError ("Exit Function");
                }
            }

        }

        return(testCondition);
    }

    static void saveUndoFile (string path)
    {
        if (File.Exists (path + ".undo")) {
            File.Delete (path + ".undo");
        }
        File.Copy (path, path + ".undo");
    }
}

```

The second optimizes GetComponent calls in Update on the local gameobject

optimizeComponents.cs

```auto
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.IO;
using UnityEngine;
using UnityEditor;
using System.Text.RegularExpressions;

public class componentOptimizer
{

    private static string line;
    private static int bracketCount;
    private static bool bracketRead = false;

    [MenuItem ("Window/Optimize/Optimize Components", false)]
    static void FindAssetsUsingSearchFilter ()
    {
        // Find all code assets
        string[] guids = AssetDatabase.FindAssets ("t:MonoScript");
        Debug.LogError (guids.Length + " Strings found");
        bool inUpdate = false;
        bool inAwake = false;
        bool inStart = false;
        bool inClass = false;
        bool writtenVars = false;
        bool written = false;

        foreach (string guid in guids) {
            int stringCount = 0;
            bracketCount = 0;
            inUpdate = false;
            inAwake = false;
            inStart = false;
            inClass = false;
            written = false;
            bracketRead = false;
            writtenVars = false;
            written = false;
            Debug.Log (AssetDatabase.GUIDToAssetPath (guid));
            if (!AssetDatabase.GUIDToAssetPath (guid).Contains ("Editor")) {
                saveUndoFile (AssetDatabase.GUIDToAssetPath (guid));
                StreamReader input = new StreamReader (AssetDatabase.GUIDToAssetPath (guid));
                StreamWriter output = new StreamWriter ("Assets/temp.txt");
                List<string> newVariables = new List<string> ();
                List<string> newInitializer = new List<string> ();
                int componentCount = 0;

                while ((line = input.ReadLine ()) != null) {
                    //Debug.LogError ("Read line " + line);
                    bracketRead = false;

                    inUpdate = inFunction ("Update(", "Update (", inUpdate, 0);

                    if ((inUpdate) && ((line.Contains ("gameObject.GetComponent")) || (line.Contains ("\tGetComponent")) || (line.Contains (" GetComponent")))) {
                        Debug.LogError ("String found");
                        Regex expression = new Regex (@"GetComponent<.*?>");
                        MatchCollection results = expression.Matches (line);

                        foreach (Match result in results) {
                            Debug.LogError (result);
                            string compName = result.Value.Substring (13, result.Value.Length - 14);
                            newVariables.Add (compName);
                            newInitializer.Add (compName + "Cache" + (newVariables.Count - 1).ToString () + "=GetComponent<" + compName + ">();");
                            //Debug.LogError (newVariables [newVariables.Count - 1]);
                        }
                    }

                }

                input.BaseStream.Seek (0L, SeekOrigin.Begin);
                bracketCount = 0;
                inUpdate = false;
                inAwake = false;
                inStart = false;
                inClass = false;
                written = false;
                bracketRead = false;
                writtenVars = false;
                written = false;

                while ((line = input.ReadLine ()) != null) {
                    //Debug.LogError ("Read line " + line);

                    bracketRead = false;

                    inUpdate = inFunction ("Update(", "Update (", inUpdate, 1);
                    inStart = inFunction ("Start(", "Start (", inStart, 1);
                    inAwake = inFunction ("Awake(", "Awake (", inAwake, 1);
                    inClass = inFunction ("class " + Path.GetFileNameWithoutExtension (AssetDatabase.GUIDToAssetPath (guid)), "class " + Path.GetFileNameWithoutExtension (AssetDatabase.GUIDToAssetPath (guid)), inClass, 0);

                    if ((inUpdate) && ((line.Contains ("gameObject.GetComponent")) || (line.Contains ("\tGetComponent")) || (line.Contains (" GetComponent")))) {
                        Debug.LogError ("String found");
                        Regex expression = new Regex (@"GetComponent<.*?>");
                        MatchCollection results = expression.Matches (line);

                        foreach (Match result in results) {
                            Debug.LogError (result);
                            string compName = result.Value.Substring (13, result.Value.Length - 14);
                            line = line.Replace ("GetComponent<" + compName + ">()", compName + "Cache" + componentCount);
                            line = line.Replace ("GetComponent<" + compName + "> ()", compName + "Cache" + componentCount);
                            componentCount++;
                        }

                    }

                    // Write the current line
                    output.Write (line);
                    output.WriteLine ();

                    if ((inClass) && (!writtenVars) && (bracketCount == 1)) {
                        output.WriteLine ();
                        int componentCount2 = 0;
                        foreach (string vars in newVariables) {
                            output.Write (vars + " " + vars + "Cache" + componentCount2 + ";");
                            output.WriteLine ();
                            componentCount2++;
                        }

                        output.WriteLine ();
                        writtenVars = true;
                    }

                    if ((inStart) && (!written) && (bracketCount == 2)) {
                        output.WriteLine ();

                        foreach (string vars in newInitializer) {
                            output.Write (vars);
                            output.WriteLine ();
                        }

                        output.WriteLine ();
                        written = true;
                    }

                    if ((inAwake) && (!written) && (bracketCount == 2)) {
                        output.WriteLine ();

                        foreach (string vars in newInitializer) {
                            output.Write (vars);
                            output.WriteLine ();
                        }

                        output.WriteLine ();

                        written = true;
                    }
                }

                output.Close ();
                input.Close ();

                if (written) {
                    File.Delete (AssetDatabase.GUIDToAssetPath (guid));
                    File.Move ("Assets/temp.txt", AssetDatabase.GUIDToAssetPath (guid));
                } else {
                    File.Delete ("Assets/temp.txt");
                }
            }

        }
        
    }

    static bool inFunction (string search1, string search2, bool testCondition, int braceMatch)
    {
        if ((line.Contains (search1)) || (line.Contains (search2))) {
            testCondition = true;
            if ((line.Contains ("{")) && (!bracketRead)) {
                bracketRead = true;
                bracketCount++;
            }
            Debug.LogError ("In Function " + search1);
            Debug.LogError (bracketCount);
        } else {
        
            if (testCondition) {
                if ((line.Contains ("{")) && (!bracketRead)) {
                    bracketRead = true;
                    bracketCount++;
                    Debug.LogError ("Open function " + bracketCount);
                }

                if ((line.Contains ("}")) && (!bracketRead)) {
                    bracketRead = true;
                    bracketCount--;
                    Debug.LogError ("Close function " + bracketCount);
                }

                if ((bracketCount == braceMatch)) {
                    testCondition = false;
                    Debug.LogError (bracketCount);
                    Debug.LogError ("Exit Function");
                }
            }

        }

        return(testCondition);
    }

    static void saveUndoFile (string path)
    {
        if (File.Exists (path + ".undo")) {
            File.Delete (path + ".undo");
        }
        File.Copy (path, path + ".undo");
    }
}

```

---

<div class="post-metadata">

### Author: ![lordofduct](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/lordofduct/32/890751_2.png) [@lordofduct](https://discussions.unity.com/u/lordofduct)
#### Post date: [February 17, 2017, 4:39am UTC](https://discussions.unity.com/t/automatic-optimizations-free-editor-code/655679/2 "2017-02-17T04:39:19Z")

</div>

> [@](#):
>
> First one replaces string in update function with hardcoded string set in start to remove garbage collection

Huh?

Could you show an example of what it’s SUPPOSED to be doing here? How would I even know what ‘unoptimized’ code I would have to be optimized and run this on.

Especially since I have no idea what this even means…

> [@](#):
>
> The second optimizes GetComponent calls in Update on the local gameobject

This one is kind of clearer… I’m assuming you mean it moves any ‘GetComponent’ calls done in Update to be done in Start/Awake?

Is there any safe guards put in for if my Start/Awake method is an override or anything?

Also, what about variable name collisions, does it safeguard against that?

---

<div class="post-metadata">

### Author: ![image28\_1](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/image28_1/32/293546_2.png) [@image28\_1](https://discussions.unity.com/u/image28_1)
#### Post date: [February 17, 2017, 4:52am UTC](https://discussions.unity.com/t/automatic-optimizations-free-editor-code/655679/3 "2017-02-17T04:52:20Z")

</div>

All valid points. The first program find strings in code ( it actually should only do it in Update and Fixed update which it doesn’t, will fix that ) and generates a string manager singleton to store all stings in, rather than creating garbage for the strings every frame.

For the component optimizer it takes the component name and creates a variable appending Cache to the component name, but there could be variable collisions, will have to look into it further

Thanks for the feedback,  
I’m aware automatic code modification can be dangerous stuff.

---

<div class="post-metadata">

### Author: ![image28\_1](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/image28_1/32/293546_2.png) [@image28\_1](https://discussions.unity.com/u/image28_1)
#### Post date: [February 17, 2017, 5:01am UTC](https://discussions.unity.com/t/automatic-optimizations-free-editor-code/655679/4 "2017-02-17T05:01:06Z")

</div>

Wrote it more for improving old finished projects in a hurry, but haven’t tested much yet.

---

<div class="post-metadata">

### Author: ![lordofduct](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/lordofduct/32/890751_2.png) [@lordofduct](https://discussions.unity.com/u/lordofduct)
#### Post date: [February 17, 2017, 5:01am UTC](https://discussions.unity.com/t/automatic-optimizations-free-editor-code/655679/5 "2017-02-17T05:01:56Z")

</div>

> [@](#):
>
> All valid points. The first program find strings in code ( it actually should only do it in Update and Fixed update which it doesn’t, will fix that ) and generates a string manager singleton to store all stings in, rather than creating garbage for the strings every frame.

Still don’t understand what you mean…

Show me an example of unoptimized code, and then what it would look like after this script was ran.

---

<div class="post-metadata">

### Author: ![image28\_1](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/image28_1/32/293546_2.png) [@image28\_1](https://discussions.unity.com/u/image28_1)
#### Post date: [February 17, 2017, 5:15am UTC](https://discussions.unity.com/t/automatic-optimizations-free-editor-code/655679/6 "2017-02-17T05:15:59Z")

</div>

Something like this. It’s a real micro optimization, but in mobile development thats important.  
Another improvement would be to replace string concatenations with string.Format for less garbage.

```auto
void Update()
{
  textScript.text = "Frames: " + framecount;
}

```

```auto
void Update()
{
  textScript.text = stringManager.Instance.filename1 + framecount;
}

```

---

<div class="post-metadata">

### Author: ![image28\_1](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/image28_1/32/293546_2.png) [@image28\_1](https://discussions.unity.com/u/image28_1)
#### Post date: [February 17, 2017, 7:34am UTC](https://discussions.unity.com/t/automatic-optimizations-free-editor-code/655679/7 "2017-02-17T07:34:35Z")

</div>

@lordofduct thanks for replying, I consider anyone with over 1000 post a unity legend. Appreciate the time you gave to respond.

---

<div class="post-metadata">

### Author: ![Timelog](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/timelog/32/307301_2.png) [@Timelog](https://discussions.unity.com/u/Timelog)
#### Post date: [February 17, 2017, 8:05am UTC](https://discussions.unity.com/t/automatic-optimizations-free-editor-code/655679/8 "2017-02-17T08:05:14Z")

</div>

I’m not sure why you’d want to create a singleton for the strings though? Why not make it a static class with constants in it as it seems there is no management being done by the class in the firsts place? In general I am against using Singletons altogether, though I can see some uses for them for specific management classes that you might want some control over, but in this case if it’s just for holding a bunch of strings, I’d go with a simple static class.

I can see some usefulness in this tool for sure for new developers, though I might assume most experienced devs don’t need it, as such, might I suggest also putting a message in it reminding anyone using it that using hardcoded strings and GetComponent all over the place is a bad idea ^.^

---

<div class="post-metadata">

### Author: ![lordofduct](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/lordofduct/32/890751_2.png) [@lordofduct](https://discussions.unity.com/u/lordofduct)
#### Post date: [February 17, 2017, 8:07am UTC](https://discussions.unity.com/t/automatic-optimizations-free-editor-code/655679/9 "2017-02-17T08:07:56Z")

</div>

OK… I had a sneaking suspicion that’s what you were shooting for.

Just so you know, string literals are treated as constants. They don’t generate garbage. They are literally part of your program code.

The string generated from the literal "Frames: " and ‘framecount’, that will generate garbage, because it’s a brand new string that can’t be optimized at compile time… since it’s runtime dependant… it’s variable based on what framecount is at the moment of creation.

Case in point…

```auto
void Update()
{
    textScript.text = "Frames: ";
}

```

Creates NO garbage whatsoever. (if any garbage does appear… it’s not the literal, and maybe implementation behind the ‘text’ property… no idea what you’re actually referencing here)

…

With that said, lets pretend that it did for the sake of critique of another aspect of the the example code.

The Singleton ‘StringManager’ doesn’t have to be a Singleton. And is actually a bit overkill. Why not just make is a static class, with static readonly fields (or better… constants).

…

But again… C# takes care of all this for you.

string literals/constants are well managed by the compiler. So much so that duplicate literals are actually pooled identically. (note, the compiler used by unity might not have this duplicate optimization built in… but even if it doesn’t, no garbage is generated, only the programs memory footprint would be slightly larger).

More literals does mean more memory used. But used memory isn’t the same as garbage… garbage is used memory that is available to be recycled. A constant/literal takes up a block of memory that is constantly used… never being recycled for anything but what it is, for the life of the program.

---

<div class="post-metadata">

### Author: ![image28\_1](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/image28_1/32/293546_2.png) [@image28\_1](https://discussions.unity.com/u/image28_1)
#### Post date: [February 17, 2017, 8:52am UTC](https://discussions.unity.com/t/automatic-optimizations-free-editor-code/655679/10 "2017-02-17T08:52:15Z")

</div>

After looking at 6 released games for steam I though some optimization coulding help. I’m a bit the opposite, I use one or two singletons in a game and avoid statics.

Agree with the message about using GetComponent, although I find a lot of pc developers still do it

> [@Timelog](#):
>
> I’m not sure why you’d want to create a singleton for the strings though? Why not make it a static class with constants in it as it seems there is no management being done by the class in the firsts place? In general I am against using Singletons altogether, though I can see some uses for them for specific management classes that you might want some control over, but in this case if it’s just for holding a bunch of strings, I’d go with a simple static class.
> 
> I can see some usefulness in this tool for sure for new developers, though I might assume most experienced devs don’t need it, as such, might I suggest also putting a message in it reminding anyone using it that using hardcoded strings and GetComponent all over the place is a bad idea ^.^

---

<div class="post-metadata">

### Author: ![image28\_1](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/image28_1/32/293546_2.png) [@image28\_1](https://discussions.unity.com/u/image28_1)
#### Post date: [February 17, 2017, 8:54am UTC](https://discussions.unity.com/t/automatic-optimizations-free-editor-code/655679/11 "2017-02-17T08:54:58Z")

</div>

I’ll have to look into this, ( weekend been drinking ), maybe I have been misinformed.

> [@lordofduct](#):
>
> OK… I had a sneaking suspicion that’s what you were shooting for.
> 
> Just so you know, string literals are treated as constants. They don’t generate garbage. They are literally part of your program code.
> 
> The string generated from the literal "Frames: " and ‘framecount’, that will generate garbage, because it’s a brand new string that can’t be optimized at compile time… since it’s runtime dependant… it’s variable based on what framecount is at the moment of creation.
> 
> Case in point…
> 
> ```auto
> void Update()
> {
> textScript.text = "Frames: ";
> }
> 
> ```
> 
> Creates NO garbage whatsoever. (if any garbage does appear… it’s not the literal, and maybe implementation behind the ‘text’ property… no idea what you’re actually referencing here)
> 
> …
> 
> With that said, lets pretend that it did for the sake of critique of another aspect of the the example code.
> 
> The Singleton ‘StringManager’ doesn’t have to be a Singleton. And is actually a bit overkill. Why not just make is a static class, with static readonly fields (or better… constants).
> 
> …
> 
> But again… C# takes care of all this for you.
> 
> string literals/constants are well managed by the compiler. So much so that duplicate literals are actually pooled identically. (note, the compiler used by unity might not have this duplicate optimization built in… but even if it doesn’t, no garbage is generated, only the programs memory footprint would be slightly larger).
> 
> More literals does mean more memory used. But used memory isn’t the same as garbage… garbage is used memory that is available to be recycled. A constant/literal takes up a block of memory that is constantly used… never being recycled for anything but what it is, for the life of the program.

---

<div class="post-metadata">

### Author: ![image28\_1](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/image28_1/32/293546_2.png) [@image28\_1](https://discussions.unity.com/u/image28_1)
#### Post date: [February 17, 2017, 7:36pm UTC](https://discussions.unity.com/t/automatic-optimizations-free-editor-code/655679/12 "2017-02-17T19:36:55Z")

</div>

Running the code on something larger than a test project. Using the code I wrote for the indievspewdiepie gamejam (PickleRunner) as a testing bed. Have run into some bugs, fixes coming soon.

---

<div class="post-metadata">

### Author: ![image28\_1](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/image28_1/32/293546_2.png) [@image28\_1](https://discussions.unity.com/u/image28_1)
#### Post date: [February 17, 2017, 7:43pm UTC](https://discussions.unity.com/t/automatic-optimizations-free-editor-code/655679/13 "2017-02-17T19:43:36Z")

</div>

> [@image28\_1](#):
>
> Running the code on something larger than a test project. Using the code I wrote for the indievspewdiepie gamejam (PickleRunner) as a testing bed. Have run into some bugs, fixes coming soon.

There were some variable collisions among other things

---

<div class="post-metadata">

### Author: ![image28\_1](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/image28_1/32/293546_2.png) [@image28\_1](https://discussions.unity.com/u/image28_1)
#### Post date: [February 17, 2017, 8:17pm UTC](https://discussions.unity.com/t/automatic-optimizations-free-editor-code/655679/14 "2017-02-17T20:17:04Z")

</div>

Some background about the project. I’m working on building a backpack computer system, but I want to be able to play games on it and currently a lot of games run just slightly too slow on the 5w micro intel board I have for the system. So looking into various different ways of improving the games performance.

---

<div class="post-metadata">

### Author: ![TaleOf4Gamers1](https://avatars.discourse-cdn.com/v4/letter/t/c77e96/32.png) [@TaleOf4Gamers1](https://discussions.unity.com/u/TaleOf4Gamers1)
#### Post date: [February 17, 2017, 8:23pm UTC](https://discussions.unity.com/t/automatic-optimizations-free-editor-code/655679/15 "2017-02-17T20:23:59Z")

</div>

While I cant vouch for its usefulness in its current state I can definitely see this becoming a “thing” especially as Unity is supposed to be a “newbie” friendly engine.

---

<div class="post-metadata">

### Author: ![Suddoha](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/suddoha/32/110358_2.png) [@Suddoha](https://discussions.unity.com/u/Suddoha)
#### Post date: [February 17, 2017, 8:47pm UTC](https://discussions.unity.com/t/automatic-optimizations-free-editor-code/655679/16 "2017-02-17T20:47:14Z")

</div>

It’s also referred to as “interning strings”.

You can also manually intern strings.e.g some that you’ve created during runtime, some which are read from other resources and might be used alot.

There are quite a few benefits, especially for the literals that are used in source code. You could compare 2 literals lots of times, it wouldn’t take as long as comparing strings that are generated / not interned due to the fact that interned strings can be compared by reference. A modern compiler does quite a lot of optimizations.

* * *

So while this isn’t actually an issue, the general idea improves other qualities of source code. Maintainability in the first place.  
You can often find source code that uses literals explicitly written throughout a whole project. Once a literal changes you’ll be busy replacing all those.  
That’s a nice opportunity to implement something similar to that idea which you have in mind, even though it’s often a good idea to seperate the different domains. In regards to Unity, you might want to define something like a static Tag class, which provides all the tags via constant variables.  
If you need to change a tag, it can be done in that one specific place (and ofc in the editor).

For existing projects, that can be done in a similar fashion to your approach.

* * *

Last but not least, one thing that you might also want to take care of when processing source files are documentations, comments, regions (and other preprocessor directives / symbols). These should (I’d say must) be left out when you process the files.  
Remember that comments can start anywhere in a line, can span over several lines, can even be inserted in between like

```auto
if( a && b /* && c */ ...)

```

While the above also counts for GetComponent, you’d actually have to analize if the return value is directly used or if it’s already an assignment to a cached variable and so on.

You’d literally have to cover every single clase, otherwise you could rather quickly mess up clean code.

It’s quite some work to do…

---

<div class="post-metadata">

### Author: ![image28\_1](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/image28_1/32/293546_2.png) [@image28\_1](https://discussions.unity.com/u/image28_1)
#### Post date: [February 17, 2017, 9:12pm UTC](https://discussions.unity.com/t/automatic-optimizations-free-editor-code/655679/17 "2017-02-17T21:12:56Z")

</div>

Yeah was aware of the comment issue. Another way to do it would to be to use Reflection in some way, but haven’t looked into using reflection that way yet ( but it would avoid the comment issue )

---

<div class="post-metadata">

### Author: ![image28\_1](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/image28_1/32/293546_2.png) [@image28\_1](https://discussions.unity.com/u/image28_1)
#### Post date: [February 17, 2017, 10:01pm UTC](https://discussions.unity.com/t/automatic-optimizations-free-editor-code/655679/18 "2017-02-17T22:01:57Z")

</div>

Updated the componentOptimizer still has a few issues, got 8 compile errors on Pickle Runner for rare code formating conditions. But works a lot better now.

---

<div class="post-metadata">

### Author: ![image28\_1](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/image28_1/32/293546_2.png) [@image28\_1](https://discussions.unity.com/u/image28_1)
#### Post date: [February 17, 2017, 10:03pm UTC](https://discussions.unity.com/t/automatic-optimizations-free-editor-code/655679/19 "2017-02-17T22:03:01Z")

</div>

> [@TaleOf4Gamers\_1](#):
>
> While I cant vouch for its usefulness in its current state I can definitely see this becoming a “thing” especially as Unity is supposed to be a “newbie” friendly engine.

Thanks I’ll keep working on it during the weekends. Eventually it might become something

---

<div class="post-metadata">

### Author: ![image28\_1](https://dub1.discourse-cdn.com/unity/user_avatar/discussions.unity.com/image28_1/32/293546_2.png) [@image28\_1](https://discussions.unity.com/u/image28_1)
#### Post date: [February 17, 2017, 10:07pm UTC](https://discussions.unity.com/t/automatic-optimizations-free-editor-code/655679/20 "2017-02-17T22:07:37Z")

</div>

Will work on the stringOptimizer for a bit before calling it a morning. Make sure it runs on a larger project

[Next page](https://discussions.unity.com/t/automatic-optimizations-free-editor-code/655679.md?page=2)
