duanniedang3946 2017-07-18 08:23
浏览 122
已采纳

PHP:Hashtable优化

I have two static hashtables in my program:

public static $labels = [
    'id' => 'ID',
    'name' => 'Name',
    'email' => 'E-mail',
    'password' => 'Password',
];

public static $columnTypes = [
    'id' => 'number',
    'name' => 'text',
    'email' => 'text',
    'password' => 'text',
];

First is for the labels of the database columns and the second for each type (necessary for filtering).

My problem is that I often need to get the type of a column by its label what leads to speed issues (hashtables are pretty slow in this direction right?).

My approaches would be the following:

  1. Type a hashtable label => type which is bad because I have to repeat myself and there is no support for other languages
  2. Create the label => type hashtable in a static content on runtime (is this possible in php?)

Are there better approaches or best practices for this issue and is the second approach possible in php? (maybe with a small example ;)

  • 写回答

2条回答 默认 最新

  • donglisi8644 2017-07-18 08:38
    关注

    Call array_flip in the class constructor. To avoid repeating it, check whether the flipped array is already set.

    class YourClass {
        public static $labels = [
            'id' => 'ID',
            'name' => 'Name',
            'email' => 'E-mail',
            'password' => 'Password',
        ];
        public static $labels_flipped = null;
    
        public function __construct() {
            if (!$labels_flipped) {
                $labels_flipped = array_flip($labels);
            }
            ...
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 AttributeError: 'NoneType' object has no attribute 'drop_duplicates'报错
  • ¥15 编写c++计算器,要求如下
  • ¥15 以下代码,运行结果报错
  • ¥15 Vivado仿真数据出错
  • ¥15 银河麒麟不支持vant等前端框架怎么办?
  • ¥15 vue3的子组件在父页面调用不显示不生效问题
  • ¥15 cadence PEX
  • ¥15 phython创建了文件 显示在项目下面,但运行不了,运行时还是运行main文件,并且说main文件不允许并行运行
  • ¥20 C++哈希表的设计构造哈希表
  • ¥15 FutureWarning:不推荐使用空或全 NA 条目的 DataFrame 串联行为。怎么改呢?