简体   繁体   中英

Understanding Time Complexity with Set Properties

I am attempting to reduce the lines in my code as a means to improve the execution speed of my windows application. So far, I've come to understand the usefulness of using properties when it comes to adding conditions within the get and set fields. I am not certain though if relying on properties helps improve the time complexity in comparison to setting a basic value followed by conditional statements in certain methods. I will provide an example on what I did first and what I improved. If anyone can share some advice on if the current improvement helps reduce processing time as well as if it follows the simplest Big-O Notation that is hopefully O(n), I'd appreciate the feedback.

Old

public float tempP1 = 1.0f;
public void addToP1() {
        tempP1 += 0.4f;
        tempP1 = (tempP1 > 2.0f) ? 2.0f : tempP1;
}

New

private float _tempP1 = 1.0f;
public float tempP1 { get { return this._tempP1; }
        set {
                value = (value > 2.0f) ? 2.0f : value;
                this._tempP1 = value;
        }
}

public void addToP1() {
        tempP1 += 0.4f;
}

Reducing the number of lines of code does not always imply the improvement of the execution speed.

What determines the speed is first the number of method calls (the properties are a calling to getters and setters), as well as typecast, datatypes (arrays or List<> for example), loops (for vs foreach) and condition tests, calculations, and things such as heap and stack usage, memory access, I/O access, hardware and software interrupts...

To improve speed you should: reduce methods calls, eliminates useless code, carefully select types, use for instead or foreach, avoid Linq, use StringBuilder instead of String to manipulate big strings...

Your "old" code (5 lines) is nearly optimized as-is.

Your "new" code (10 lines) is not because of the call introduced with the get and set even if the compiler optimize them.

But you can do better using a boolean:

bool reached = false;
public float tempP1 = 1.0f;
public void addToP1()
{
  if ( reached ) return;
  tempP1 += 0.4f;
  reached = tempP1 > 2.0f;
  if ( reached )
    tempP1 = 2.0f;
}

You can compile in release mode and check that optimization is enabled in the project settings/build.

Someone could probably find better optimization but it would be using esoteric code and this is generally not recommended.

You can of course use IL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM