Working with large strings and arrays (few MB) php does large amount of reallocs. We can reduce them by preallocating memory when output size can be predicted. How about applying such patch? It would be even better if smart strings expose better allocation api than smart_str_alloc.

Regards,
Wojtek Meler
Index: string.c
===================================================================
RCS file: /repository/php-src/ext/standard/string.c,v
retrieving revision 1.333.2.52.2.3
diff -u -r1.333.2.52.2.3 string.c
--- string.c	1 Jan 2006 13:46:58 -0000	1.333.2.52.2.3
+++ string.c	20 Feb 2006 10:37:13 -0000
@@ -829,12 +829,14 @@
 	HashPosition   pos;
 	smart_str      implstr = {0};
 	int            numelems, i = 0;
+	size_t newlen; //used by smart_str_alloc
 
 	numelems = zend_hash_num_elements(Z_ARRVAL_P(arr));
 
 	if(numelems == 0) {
 		RETURN_EMPTY_STRING();
 	}
+	smart_str_alloc((&implstr),numelems*Z_STRLEN_P(delim),0);
 
 	zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(arr), &pos);
 	while (zend_hash_get_current_data_ex(Z_ARRVAL_P(arr), 
@@ -846,6 +848,8 @@
 		smart_str_appendl(&implstr, Z_STRVAL_PP(tmp), Z_STRLEN_PP(tmp));
 		if (++i != numelems) {
 			smart_str_appendl(&implstr, Z_STRVAL_P(delim), Z_STRLEN_P(delim));
+			newlen  = numelems*(implstr.len/i)-implstr.len;
+			smart_str_alloc((&implstr),newlen,0);
 		}
 		zend_hash_move_forward_ex(Z_ARRVAL_P(arr), &pos);
 	}
@@ -1924,6 +1928,10 @@
 
 	key = emalloc(maxlen+1);
 	pos = 0;
+	{
+		size_t newlen;
+		smart_str_alloc((&result),slen,0);
+	}
 
 	while (pos < slen) {
 		if ((pos + maxlen) > slen) {
@@ -2556,6 +2564,9 @@
 	char *r;
 	char *end = haystack + length;
 	smart_str result = {0};
+	size_t newlen; //used by smart_str_alloc
+
+	smart_str_alloc(&result,length,0);
 
 	for (p = haystack;
 			(r = php_memnstr(p, needle, needle_len, end));

-- 
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to