Skip to content
Advertisement

Which is faster php date functions or carbon?

Carbon is simple PHP API extension for DateTime. I want to know that we can use datetime functions using by installing carbon via composer.

which is faster php datetime functions or carbon ?

Advertisement

Answer

I did some testing regarding your comment comparing DateTime to Carbon functions:

Calling Carbon::now() vs. new DateTime() 100.000 times:

<?php

require "Carbon.php";

use CarbonCarbon;

$carbonTime = 0;
for ($i = 0; $i < 100000; $i++)
{
    $start = microtime(true);
    $time = Carbon::now();  
    $end = microtime(true);

    $carbonTime += $end - $start;
}

echo "carbonTime: ".$carbonTime."n";

$phpTime = 0;
for ($i = 0; $i < 100000; $i++)
{
    $start = microtime(true);
    $time = new DateTime();
    $end = microtime(true);

    $phpTime += $end - $start;
}

echo "phpTime: ".$phpTime."n";

Results from 5 runs (meaning 5x 100.000 calls):

$ php test.php
carbonTime: 5.1191372871399
phpTime: 0.42734241485596

$ php test.php
carbonTime: 5.05357670784
phpTime: 0.41754531860352

$ php test.php
carbonTime: 5.4670262336731
phpTime: 0.42954564094543

$ php test.php
carbonTime: 5.0321266651154
phpTime: 0.44966721534729

$ php test.php
carbonTime: 5.1405448913574
phpTime: 0.4540810585022

Confirming what I initially wrote:

Since Carbon inherits DateTime it actually adds a little overhead to those calls (Carbon -> DateTime instead of directly DateTime). The main purpose of Carbon is not to be faster than DateTime, but to enhance it’s functionality with commonly used functions.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement