How to efficiently parse 'yyyymmdd' in cs (a c/c++ guy's question)?

B

Bogdan

Hi,

I primarily develop in c/c++ but need to write a relatively simple code in
cs.

I need to parse year, month, and day from strings representing dates as
'yyyymmdd'.

What is the most efficient (speed-wise and memory-wise) way to do that in
cs?

I could use string.IndexOf()/string.Substring()/Int32.Parse() combination
but this seems to create a lot of new string objects.
Is there a better way?

Thanks,
Bogdan
 
J

Jeroen Mostert

Bogdan said:
I primarily develop in c/c++ but need to write a relatively simple code in
cs.

I need to parse year, month, and day from strings representing dates as
'yyyymmdd'.

What is the most efficient (speed-wise and memory-wise) way to do that in
cs?
You forgot developer-time-wise, which is the most important of all.

DateTime.ParseExact(s, "yyyyMMdd", CultureInfo.InvariantCulture);
I could use string.IndexOf()/string.Substring()/Int32.Parse() combination
but this seems to create a lot of new string objects.

..NET happens to be very good at handling the creation and near-immediate
discarding of new objects, so that's not necessarily a problem.
Is there a better way?
In the unlikely case that DateTime isn't good enough (and don't assume this
without testing) you can extract the values without creating substrings, by
simply doing things the hard way (if you're familiar with C, this should
come natural). Slightly obfuscated for your viewing pleasure (disclaimer: I
have no idea what the performance of this is and I'm not testing because I'd
never use it):

if (s.Length != 8) /* fail */;
for (int n = 0; n != 8; ++n) if (s[n] < '0' || s[n] > '8') /* fail */;
int year = s[3] + 10 * (s[2] + 10 * (s[1] + 10 * s[0])) - 53328;
int month = s[5] + 10 * s[4] - 528;
int day = s[7] + 10 * s[6] - 528;
 
B

Bogdan

Jeroen Mostert said:
You forgot developer-time-wise, which is the most important of all.

DateTime.ParseExact(s, "yyyyMMdd", CultureInfo.InvariantCulture);

ParseExact() is ideal in my case.
Thanks,
Bogdan
 
J

Jeroen Mostert

Jeroen said:
for (int n = 0; n != 8; ++n) if (s[n] < '0' || s[n] > '8') /* fail */;

Behold the dangers of premature optimization. This code is casting out nines
when it really shouldn't.
 
J

Jesse Houwing

* Bogdan wrote, On 6-10-2009 23:26:
ParseExact() is ideal in my case.
Thanks,
Bogdan

Also look at TryParseExact. It allows you to detect failed parses
without having to catch exceptions. (talking about efficient)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top