PHP - Many variables or One array?

后端 未结 6 862
半阙折子戏
半阙折子戏 2020-12-14 08:52

I have a question, what is more faster ...

  1. I make many variables that contain all of my data, or
  2. I make one array in one variable that contai
6条回答
  •  余生分开走
    2020-12-14 09:18

    People here say that arrays are faster. But arrays are also variables. if you use an array - you still need to access it like any variable and additionally you need to access an item in array. So, it looks to me that array used like a storage for variables is not the best idea.

    Additionally - arrays are used to store some array data. Like category id => category name pairs, for instance.

    $catId1 = "Category 1";
    $catId2 = "Category 2";
    $catId3 = "Category 3";
    

    Code like above would be... strange. You are loosing many features of an array, for instance, can't go through all categories in for loop. So, for array data - array is what you need.

    Once you have different kinds of data (talking about meaning of that data, not its type like integer or string) you should better use variables:

    $requested_category = 1;
    $requested_category_name = "Some category";
    $category_processing_result = "Ok"; 
    

    instead of array:

    $varsArray['requested_category'] = 1;
    $varsArray['requested_category_name'] = "Some category";
    $varsArray['category_processing_result'] = "Ok"; 
    

    With variables any IDE will help you to write those names, such code is easier to read and support. And that is more important, as for me.

    Even if they are slower somehow, or take more memory - that is not a worst problem in terms of speed/memory usage for sure.

提交回复
热议问题