Dominating
Dominating

Reputation: 2930

Memory or time to choose when using Directory.GetCurrent?

I was wandering which is best to do:

string tmp = Directory.GetCurrentDirectory();
string path = tmp.Substring(0,tmp.LastIndexOf('\\'));

or

string path = Directory.GetCurrentDirectory().Substring(0, Directory.GetCurrentDirectory().LastIndexOf('\\'));

when I want to take the root Directory of the current one? To call twice the method or to do a string variable which have to be removed from garbage collector after this?

Upvotes: 1

Views: 85

Answers (3)

R. Martinho Fernandes
R. Martinho Fernandes

Reputation: 234644

Regarding the "issue" with the garbage collector: the garbage collector does not collect variables, it collects objects. A string object is still created with your second approach, you're just not taking it for your own use.

They're almost the same, with the difference that the second calls Directory.GetCurrentDirectory twice, and thus creating a second string object. Contrary to what you thought, the one that places extra work on the garbage collector is the second option.

Irrelevant of performance it's much simpler and safer (no race conditions) to just store its value in a variable for further use.

To get the path of the parent directory I would use the Path.GetDirectoryName method because it makes the code much clearer, shorter and portable:

string path = Path.GetDirectoryName(tmp);

Upvotes: 3

Achinth Gurkhi
Achinth Gurkhi

Reputation: 2156

I had a look at the source code of System.IO.Directory, the GetCurrentDirectory() method makes couple of native calls, uses StringBuilder and then some processing every time the method is called. So, using the first option would be the better choice.

Upvotes: 1

Unknown
Unknown

Reputation: 411

I'd choose the first one - it's at least human-readable. I don't think you'll really gain anything by picking the 2nd snippet.

Upvotes: 0

Related Questions