How can I improve the time complexity of this code??
$s = "Name";
for($i=0; $i<strlen($s); $i++) {
//some code
}
How can I improve the time complexity of this code??
$s = "Name";
for($i=0; $i<strlen($s); $i++) {
//some code
}
It depends on PHP's implementation of Strings and strlen(). If it is O(n) (which it is in GNU's C strlen()) the complexity of OP's code would be O(n²). Moving the strlen() out of the loop would improve to O(n) in this case:
$length = strlen($s);
for($i=0; $i<$length; $i++) {
//some code
}
However if the complexity of strlen() is O(1) (e.g. C++), The code is in O(n) and you can't improve it any more.
I have to admit, that I'm not fluent in C/C++, but I guess the length is a simple attribute of a zend_string, i.e. PHP's strlen() is O(1):
ZEND_FUNCTION(strlen)
{
zend_string *s;
// [..]
RETVAL_LONG(s->len);
}