I was wondering if a function of the form

public String GetString
{
    get
    {
        return stringValue
    }
}

is faster than a fucntion of the form

public void GetString(out String value)
{
    value = stringValue;
}

:)

Recommended Answers

All 4 Replies

What you actually mean: Is a property faster than a method.

In the provided code it wont really matter as your doing such miniscule operations it is probably hard to split the difference in performance. Plus I doubt there is one as both are very simple operations.

    public string GetString()
    {
        string value = stringValue;
        return value;
    }

Would be the correct code for the method, your using an out for no real reason :)

The property is basically just a shortcut for a method that returns a value. If you looked at the il for it you would find that a get method was created by the compiler.
If you had a property called Age the generated il asm code would contain get_Age and set_Age methods.

public int Age {get;set;}

is converted to

.property instance int32 Age()
{
  .get instance int32 PropertiesExample.PropertiesClass::get_Age()
  .set instance void PropertiesExample.PropertiesClass::set_Age(int32)
}

So as far as execution speed goes, it would be the same between a GetString method that only returns a string and a property that only returns a string.

Please don't write your methods like this:

public void GetString(out String value)
{
    value = stringValue;
}

A simple return statement is shorter and easier to read. I recommend you don't write methods with out parameters unless there is truly a need for them. For an example, see Int32.TryParse or Dictionary.TryGetValue.

Also:

public String GetString
{
    get
    {
        return stringValue
    }
}

"GetString" isn't a very useful property name, and if you're not going to do anything special with stringValue, it is (once again) much shorter and more readable to use automatic properties:

public String UsefulPropertyName { get; }

Don't worry about performance yet; try and write simple, clean, readable code first. Once your application is more or less feature complete, it may already run fast enough that the extra boost won't matter. If it doesn't run as fast as you want, then use a profiler to see where the actual performance bottlenecks are. Then you can worry about how to speed them up.

My two cents: If you're writing anything worth using, the speed of a simple property retrieval really isn't going to be your worst-performing code.

Thanx guys, very usefull information. I asked this because i'm new to C# doing my first professional embedded project with managed code. I usaully write small programs in C for microcontrollers. I had a problem with my server program. Is solved now. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.