Is there some way I can optimize this C# code?
I have my code and I would like to optimize it. For me it looks like it's already optimized. Can anyone suggest how I could make it a bit more optimized?
if (target == "power")
{
return new JsonResult { Data = new { RC = new Data.AdminPower(datastoreValue).Refresh() } };
}
if (target == "notes")
{
return new JsonResult { Data = 开发者_StackOverflownew { RC = new Data.AdminNotes(datastoreValue).Refresh() } };
}
if (target == "book")
{
return new JsonResult { Data = new { RC = new Data.AdminBook(datastoreValue).Refresh() } };
}
return null;
switch statements are great for these situations:
switch(target)
{
case "power":
return new JsonResult { Data = new { RC = new Data.AdminPower(datastoreValue).Refresh() } };
case "notes":
return new JsonResult { Data = new { RC = new Data.AdminNotes(datastoreValue).Refresh() } };
case "book":
return new JsonResult { Data = new { RC = new Data.AdminBook(datastoreValue).Refresh() } };
default:
return null;
}
Dont really need the breaks tho, since it will be returning each time, but its good practice..
If you know that your method will be called more often with "book"
values, then you should put that first. Basically sort by order of frequency.
As someone else mentioned, you should put them in order of most likely to occur to minimize your total number of incorrect comparisons.
Maybe it's possible to change "power" "notes" and "book" to an enum or int representation, and that may be slightly faster than the string comparisons.
There's not a whole lot you can do that will result in any significant optimizations, though.
I don't know what's your idea about optimized, as a matter of speed, just put some 'else' before second and third 'if's but if you mean less code lines, then may be something like this could help you:
return
((target == "power") ? new JsonResult { Data = new { RC = new Data.AdminPower(datastoreValue).Refresh() } } :
((target == "notes") ? new JsonResult { Data = new { RC = new Data.AdminNotes(datastoreValue).Refresh() } } :
((target == "book") ? new JsonResult { Data = new { RC = new Data.AdminBook(datastoreValue).Refresh() } } : null))))
The only thing I would do is change the if
s to an if-elseif
chain. There isn't really anything else you can do to improve performance.
精彩评论