M
M
Max Khartanovych2015-10-10 15:43:48
Yii
Max Khartanovych, 2015-10-10 15:43:48

Yii2, activerecord cons of asArray()?

Hello!
Not so long ago, a colleague and I had a dispute about how best to work with ActiveRecord in Yii2, and in particular with the asArray();.
My colleague suggested to always or most often use this method when getting data from MySQL and build queries in such a way that you would always get a flat array with the desired data, similar to this

array(
   'id'=>1,
   'name'=>'SomeName',
   'subscribers'=>1,
   'likes'=>5,
);

the keys 'subscribers' and 'likes' are leftjoin to another table

arguing that:
  • memory consumption
  • get a simple array
  • speed

The arguments are quite strong, and my counterargument is only the convenience of developing with objects.
In a simple example, when the task is to get and display, working with asArray();obviously looks much more preferable, because really, why do we need the data that the ActiveRecord model stores, information about behavior and so on.
A small example of working with data in a comparison view
// asArray();
foreach($model as $user){
   <p><?= $user['name'] ?><p/>
   <p><?= $user['subscribers'] ?><p/>
   <p><?= $user['likes'] ?><p/>
}
// Object
foreach($model as $user){
   <p><?= $user->name ?><p/>
   <p><?= $user->subscribers->value ?><p/>
   <p><?= $user->likes->value ?><p/>
}

A colleague's test on a local vagrant image showed that for 1 thousand entries asArray(); requires 4MB of memory and objects 12MB.
The project does not include getting large data arrays in one request, but a large load must be taken into account.
Who has any thoughts on this? How advantageous is working with objects compared to arrays in the task of getting and displaying?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
H
HaruAtari, 2015-10-10
@maxkh

To use asArray() means to lose all the OOP goodies. Do not forget that in addition to the fields in the mods, there is also logic. You don't even have autocomplete buder tabot.

M
Maxim Timofeev, 2015-10-10
@webinar

In my opinion, there is no need to choose. Sometimes you need to use an array, sometimes an object. Everything depends on the situation. I think it's more convenient to initially work with objects, and then add asArray when possible when optimizing.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question