I’m parsing through a text file and a lot of what I’m doing involves code like:
int jobTypeStart = contents.IndexOf("JobType: ");
int jobTypeEnd = contents.IndexOf("\r\n", jobtypeStart);
string jobType = contents.Substring(jobtypeStart,
(jobTypeEnd - jobTypeStart )).Replace("JobType: ","");
This same basic pattern is repeated 30 different times per file and hundreds or thousands of files are in a foreach loop. Is it more efficient to declare a new variable each time, or to reuse those int variables and just change the IndexOf that I’m looking for? So for the sake of clarity, should my next block of code be:
int userNameStart = contents.IndexOf("UserName: ");
int userNameEnd = contents.IndexOf("\r\n", userNameStart);
string userName= contents.Substring(userNameStart,
(userNameEnd - userNameStart)).Replace("UserName: ","");
Or should the whole thing be more like:
int stringStart = contents.IndexOf("JobType: ");
int stringEnd = contents.IndexOf("\r\n", stringStart);
string jobType = contents.Substring(stringStart ,
(stringEnd - stringStart)).Replace("JobType: ","");
stringStart = contents.IndexOf("UserName: ");
stringEnd = contents.IndexOf("\r\n", stringStart);
string userName= contents.Substring(stringStart ,
(stringEnd - stringStart)).Replace("UserName: ","");
Or am I overcomplicating something that really doesn’t matter that much?
Cheers.
You should refactor this into a method:
and call it like
I’d favor readability in this case.