I know you’ve probably seen this topic a hundred times, and so have I, but this one has a different twist. We already know that there are many ways to get the extension of a file, but which one is the fastest? That’s what I’m going to address right now.
In each of the code examples
$file is set to
Path Info Method
To test each of the contenders I put together a script that timed the execution of 1,000,000 iterations of each command. If you would like the script you can download it here.
Sub-String Method: 0.778156 seconds
String-to-Array Method: 1.889744 seconds
Path Info Method: 2.020036 seconds
Our winner? The Sub-String Method! Next time you reach for that line of code to get a file’s extension, go for gold, and choose the Sub-String Method.