什么是更好的stdClass或(对象)数组来存储相关数据? [英] What is better stdClass or (object) array to store related data?

查看:56
本文介绍了什么是更好的stdClass或(对象)数组来存储相关数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很长一段时间以来,我一直在使用数组来存储相关字段.如果我想拥有相关的用户字段,请使用:

I have been using arrays to store related fields during a long time. If I wanted to have related user fields, I used:

$user = array(
   'id' => 27
   'name' => 'Pepe'
);

但是最近,我一直在处理对象,我更喜欢使用$ user-> id代替$ user ['id'].

But lately, I've been working a lot with objects, and I like it more to use $user->id instead of $user['id'].

我的问题:要实现面向对象的样式,您可以使用stdClass:

My question: To achieve an object oriented style, you may use stdClass:

$user = new stdClass();
$user->id = 27;
$user->name = 'Pepe';

或从数组中强制转换

$user = (object) array(
  'id' => 27
, 'name' => 'Pepe'
);

按照性能和样式的顺序,其中一个比另一个更好吗?还是您可以模糊地使用任何想要的东西?

Is one of them better than the other, in order of performance and style, or can you use whatever you want indistinctly?

谢谢!

更新: 我同意所有评论,这根本不是面向对象的,而只是将相关数据分组为一个结构.我的$ user例子不是最好的,因为这是使用带有方法,属性,等等的类的典型例子.我问是因为我有很多配置结构,例如我们的"initTable",而我想要这样的东西: /p>

Update: I agree with all the comments, this is not OOP at all, is just about having related data grouped into a structure. My $user example is not the best, because it's a typical example of using classes with method, properties, blablabla... I asked because I have a lot of config structures, such us "initTable", and I want something like:

$table => page => init => 1
               => end  => 25
          sort => field => name
               => order => asc

依此类推,我想知道什么是最好的初始化页面:

and so on, and I want to know what is better to get init page:

$table->page->init **OR** $table['page']['init']

推荐答案

基于小型测试( http://phpfiddle.org/lite/code/cz0-hyf )我可以说使用"new stdClass()"的速度比其他选项慢3倍.

Based on small test (http://phpfiddle.org/lite/code/cz0-hyf) I can say that using "new stdClass()" is about 3 times slower than other options.

这很奇怪,但是与stdClass相比,强制转换数组非常有效.

It is strange, but casting an array is done very efficiently compared to stdClass.

但是此测试仅测量执行时间.它不计量内存.

But this test meters only execution time. It does not meter memory.

P.S.我只使用phpFiddle共享代码.测试是在我的本地PC上完成的.

P.S. I used phpFiddle only to share code. Test were done at my local PC.

这篇关于什么是更好的stdClass或(对象)数组来存储相关数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆