[Phpug] Performance: Static versus Intance Methods
Kae Verens
kae at verens.com
Tue Sep 11 19:11:49 IST 2007
David Foley wrote:
> Hi all - just joined the group today and as it happens, I have a situation I
> wouldn't mind some feedback on.
>
> Ok -I've been developing a PHP String class - just a wrapper for php
> strings. It lets me do things like this:
>
> // some priori code
> $pdfFileName = new String ($item['name']);
> $pdfFileName = $pdfFileName ->toHTMLEntities("UTF-8")->replace(".pdf",
> "")->replace(".", " ");
>
> rather than this
>
> // some prior code
> $pdfFileName = $item['name'];
> $pdfFileName = htmlentities($pdfFileName, ENT_COMPAT, "UTF-8");
> $pdfFileName = str_replace(".pdf", "", $pdfFileName);
> $pdfFileName = str_replace(".", " ", $pdfFileName);
>
> Its not the most dramatic or sensible demonstration in the world, but thats
> not the point: the point is that the String class
> I'm developing has about 18 methods in all, and Im wondering about
> performance impact.in cases where lots of String
> instances are being used.
>
I do something similar in my KFM project, but to do with files and
directories. in each case, whenever a directory is referenced, a new
object would be created which reads from the database. you'll agree that
this can be a horrible drain if their are only 3 directories, but there
are 10 or more references.
the way I solved it was to use a variant of the Singleton pattern. I'll
write up how I'd do it for your class:
stringInstances=array();
class String{
function String($name=''){
// insert constructor code here
}
function __construct($name=''){
$this->String();
}
function getInstance($name=''){
global $stringInstances;
if(!isset($stringInstances[$name]))$stringInstances[$name]=new
String($name);
return $stringInstances[$name];
}
// insert other methods here
}
the reason for the archaic code is that this method is designed to work
in both PHP5 and PHP4
after the class is written, you will never initialise a string like this:
$t=new String('blah');
instead, it's initialised like this:
$t=String::getInstance('blah');
Kae
More information about the Phpug
mailing list