Skip to content

Commit afaa65e

Browse files
committed
array_map: Avoid allocation by using Z_EXTRA storage of parameters
1 parent 643810a commit afaa65e

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

ext/standard/array.c

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6854,10 +6854,10 @@ PHP_FUNCTION(array_map)
68546854
}
68556855
}
68566856

6857-
uint32_t *array_pos = ecalloc(n_arrays, sizeof(HashPosition));
68586857
array_init_size(return_value, maxlen);
68596858

68606859
if (!ZEND_FCI_INITIALIZED(fci)) {
6860+
uint32_t *array_pos = ecalloc(n_arrays, sizeof(HashPosition));
68616861
zval zv;
68626862

68636863
/* We iterate through all the arrays at once. */
@@ -6901,9 +6901,16 @@ PHP_FUNCTION(array_map)
69016901

69026902
zend_hash_next_index_insert_new(Z_ARRVAL_P(return_value), &result);
69036903
}
6904+
6905+
efree(array_pos);
69046906
} else {
69056907
zval *params = (zval *)safe_emalloc(n_arrays, sizeof(zval), 0);
69066908

6909+
/* Remember next starting point in the array, initialize those as zeros. */
6910+
for (i = 0; i < n_arrays; i++) {
6911+
Z_EXTRA(params[i]) = 0;
6912+
}
6913+
69076914
fci.retval = &result;
69086915
fci.param_count = n_arrays;
69096916
fci.params = params;
@@ -6913,15 +6920,15 @@ PHP_FUNCTION(array_map)
69136920
for (i = 0; i < n_arrays; i++) {
69146921
/* If this array still has elements, add the current one to the
69156922
* parameter list, otherwise use null value. */
6916-
uint32_t pos = array_pos[i];
6923+
uint32_t pos = Z_EXTRA(params[i]);
69176924
if (HT_IS_PACKED(Z_ARRVAL(arrays[i]))) {
69186925
while (1) {
69196926
if (pos >= Z_ARRVAL(arrays[i])->nNumUsed) {
69206927
ZVAL_NULL(&params[i]);
69216928
break;
69226929
} else if (Z_TYPE(Z_ARRVAL(arrays[i])->arPacked[pos]) != IS_UNDEF) {
69236930
ZVAL_COPY_VALUE(&params[i], &Z_ARRVAL(arrays[i])->arPacked[pos]);
6924-
array_pos[i] = pos + 1;
6931+
Z_EXTRA(params[i]) = pos + 1;
69256932
break;
69266933
}
69276934
pos++;
@@ -6933,7 +6940,7 @@ PHP_FUNCTION(array_map)
69336940
break;
69346941
} else if (Z_TYPE(Z_ARRVAL(arrays[i])->arData[pos].val) != IS_UNDEF) {
69356942
ZVAL_COPY_VALUE(&params[i], &Z_ARRVAL(arrays[i])->arData[pos].val);
6936-
array_pos[i] = pos + 1;
6943+
Z_EXTRA(params[i]) = pos + 1;
69376944
break;
69386945
}
69396946
pos++;
@@ -6946,7 +6953,6 @@ PHP_FUNCTION(array_map)
69466953
ZEND_IGNORE_VALUE(ret);
69476954

69486955
if (Z_TYPE(result) == IS_UNDEF) {
6949-
efree(array_pos);
69506956
efree(params);
69516957
RETURN_THROWS();
69526958
}
@@ -6956,7 +6962,6 @@ PHP_FUNCTION(array_map)
69566962

69576963
efree(params);
69586964
}
6959-
efree(array_pos);
69606965
}
69616966
}
69626967
/* }}} */

0 commit comments

Comments
 (0)