dsfsdfsdfsdf6455 2013-08-25 21:14
浏览 29
已采纳

数组分配性能

I saw this post, but didn't quite understand it and it didn't quite answer my question. Also - it seems to suggest that arrays are slower. I thought: that cannot be!

When all else is equal, and when aiming for speed, what is the best way to assign variables in an array?

Is this better:

$part1 = "a";
$part2 = "b";
$part3 = "c";
$part4 = "d";

(Sure, I know this doesn't allow you to interact with the data like you would with an array, but let's say you didn't need to.)

Is this better:

$part[1] = "a";
$part[2] = "b";
$part[3] = "c";
$part[4] = "d";

Is this better:

$part = array("a","b","c","d");

Or something else? And what are the mechanics behind why one is better than the others?

Also - does it depend on the number of elements being assigned? How does the answer change when talking about multidimensional arrays, different data types, or different languages? Also, does it change if I initialize the array then add elements to it?

  • 写回答

1条回答 默认 最新

  • dongme8388 2013-08-25 21:29
    关注

    An array is an array, no matter how you specify or assign variables to it. Once you create an array, it is put into memeory (unless you're utilizing SplFixedArray) and arrays in memory grow very quickly.

    Consider this article which does a deeper look into how resource intensive arrays are: http://nikic.github.io/2011/12/12/How-big-are-PHP-arrays-really-Hint-BIG.html

    From the article:

    In this post I want to investigate the memory usage of PHP arrays (and values in general) using the following script as an example, which creates 100000 unique integer array elements and measures the resulting memory usage:

    <?php
    $startMemory = memory_get_usage();
    $array = range(1, 100000);
    echo memory_get_usage() - $startMemory, ' bytes';
    

    How much would you expect it to be? Simple, one integer is 8 bytes (on a 64 bit unix machine and using the long type) and you got 100000 integers, so you obviously will need 800000 bytes. That’s something like 0.76 MBs.

    Now try and run the above code. You can do it online if you want. This gives me 14649024 bytes. Yes, you heard right, that’s 13.97 MB - eightteen times more than we estimated.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题