开发者

Preallocate string memory in PHP

Is it possible to preallocate memory for a string in PHP or to set a string to a constant fixed size?

I have a random string that is generated, it's always 32 chars long, and it currently concatenates a character on the end of the string; I'm th开发者_如何学Pythoninking that it would be more efficient if I could use a constant sized string.


You could use str_repeat() to pre-generate a string containing 32 spaces, and, then, access each character like this :

$string[3] = 'a';

Note: see String access and modification by character in tha manual, about that.


I suppose it would cause less memory (re-)allocations.

But, really :

  • you shouldn't worry about that kind of micro-optimization...
  • I'm not sure how strings are implemented in PHP (you'd have to take a look at its source-code), so not sure this idea would be better for performances.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜