C# properties allows one to access data similar to variables instead of methods. Internally, the implementation might be same. But, by looking at the code which uses properties, one thinks that, it is using variables. If we don't use properties, then, we have to use methods to get the same.
I wanted to get the data from sharepoint list, and wrote the following code. (list is a sharepoint list SPList).
for (int rowIndex = 0; rowIndex < rows; rowIndex++)
{
for (int colIndex = 0; colIndex < columns; colIndex++)
{
Console.WriteLine(list.Items[rowIndex][columnNames[colIndex]]);
}
}
The list contains around 3000 items, and each item contains around 40 columns. For this, the above code took around 17 hours. It is not a feasible option for me. So, I tried various things, and finally changed the code to below.
SPListItemCollection listItems = list.Items;
foreach (SPListItem listItem in listItems)
{
for (int colIndex = 0; colIndex < columns; colIndex++)
{
Console.WriteLine(listItem[columnNames[colIndex]]);
}
}
How much time do you think the above code would take?
It took 2 minutes.
For the people who know only C# and no other language, probably, it may not be a surprise. But, for those who have good knowledge in other languages, it does not make sense. Many developers (those who worked in other languages) think properties similar to variables. It is not intuitive to cache the value from the properties.
If there is lot of computation to be done, then they should use methods. If the data is ready and no computation/retrieval is required, then they can use properties.
While optimizing the performance for the above code, few non-developers in my team insisted me to use profiler to find out the problem in the above code. But, I did not run any profiler on the code. One non-developer ran the profiler on that code and got the results, and other non-developers insisted me to take those results. If you are a developer and know that sharepoint is a proprietary software, then I don't need to explain anything on this.
Wednesday, May 06, 2009
Abusing Properties in C#
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment