0

My question is about to make some laugh but I like keeping things clean and clear when I code, here's my question 'what is the best between both the chunks ?' :

$placeholders['createtime'] = is_null($Article->get_createtime())
                                ? 'NOW()'
                                : $Article->get_createtime();

or

$createTime = $Article->get_createtime();
$placeholders['createtime'] = is_null($createTime) ? 'NOW()' : $createTime;

I would tend to say the second one is better regarding procedural performances but as I barely know about how php manages variables into memory and functions' calls I decided to ask.

I know it also depends on the complexity of the function get_createtime() and if the function is long to process it is better to store the result in the memory, but my question stars basic getters with just a return instruction inside.

Markus
  • 3,225
  • 6
  • 35
  • 47
vdegenne
  • 12,272
  • 14
  • 80
  • 106
  • 3
    I'd say even thinking about this might be a case of **premature optimization**. If `get_createtime` is a "dumb" getter, the performance difference will most probably be negligible (you can benchmark though, to be sure). I'd prefer the second version, not because of performance, but because of *readability*. – helmbert May 10 '15 at 19:36
  • I think the second one is better because it is more readable and self explaining. When i start to read your question the first chunk of code looks too messy so i just pass it and start to read the second one and almost immediately get it – Tony May 10 '15 at 19:37

2 Answers2

0

I think the first one is more performant than the second one because the second one requires to allocate and create a new variable.

LostPhysx
  • 3,573
  • 8
  • 43
  • 73
0

If you're not strictly checking against null then I suggest using example below where you get rid of is_null() call:

$placeholders['createtime'] = $Article->get_createtime()
                              ? $Article->get_createtime()
                              : now();

I would certainly not use second one because you're allocation system resources for $createTime which is unnecessary. However, if you don't care then you should use $createTime = ''; to free up memory instead of unset($createTime);. Read up on How PHP manages variables to see why. A bit long winded but very interesting read.

BentCoder
  • 12,257
  • 22
  • 93
  • 165
  • thanks a lot for the link, it looks nice, i'll read with a cup of coffee tomorrow morning because coffee rules! – vdegenne May 10 '15 at 20:08