WarpConduit Computing

  • Quick Tips
  • Web Design & Development
  • WordPress Plugins
  • Home
  • Passphrase Generator
  • Password Generator
  • About
  • Contact

Get File Extension with PHP + Benchmark Results

February 27, 2011 by Josh Hartman

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.

Contenders

In each of the code examples $file is set to c:\\xampplite\\htdocs\\index.php.

String-to-Array Method


<?php
$ext = end(explode('.', $file));
echo $ext; // outputs 'php'
?>

Sub-String Method


<?php
$ext = substr($file, strrpos($file, '.')+1);
echo $ext; // outputs 'php'
?>

Path Info Method


<?php
$ext = pathinfo($file, PATHINFO_EXTENSION);
echo $ext; // outputs 'php'
?>

Setup

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.

Results

Get File Extension PHP Benchmark
Sub-String Method: 0.778156 seconds
String-to-Array Method: 1.889744 seconds
Path Info Method: 2.020036 seconds

Winner

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.


<?php
$ext = substr($file, strrpos($file, '.')+1);
echo $ext; // outputs 'php'
?>

Filed Under: Web Design & Development Tagged With: benchmark, extension, file, php

Connect

  • Facebook
  • GitHub
  • RSS
  • Twitter
  • YouTube

Recent Posts

  • Extremely Useful Applications for Web Development and IT Tasks
  • Installing BookStack Wiki on cPanel Shared Hosting
  • Media (MIME) Type Reference List

Tags

automatic benchmark cbc cipher class comparisons cpanel credit memo css decrypt encrypt font gzip htaccess html image increment javascript jquery list magento mcrypt mysql number old opencart order php profiling random redirect repository rijndael shipment software strict ubuntu url wincachegrind windows windows 7 wordpress xampp xdebug xss

Blogroll

  • CodeIgniter
  • Fusion Forward
  • jQuery
  • Nettuts+
  • Smashing Magazine

© 2023 WarpConduit Computing. All Rights Reserved.