CodeIgniter - 加载库(如果尚未加载) [英] CodeIgniter - Load libraries if not already loaded

查看:99
本文介绍了CodeIgniter - 加载库(如果尚未加载)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的是在网站的许多不同点上加载库(如果它们尚未加载)(CI的库或自定义库)。所以我想做一个检查这个。

What I'm trying to do is to load libraries if they not already loaded (either CI's libraries, either custom ones) on many different points of a website. So I want to do a check on this.

我对Loader库进行了搜索,发现了is_loaded()函数,所以我可以这样做: / p>

I have done a search on Loader library and found the is_loaded() function, so I could do this for example:

if ($this->load->is_loaded('form_validation') === false) {
    $this->load->library('form_validation');            
}

这个奇怪的事情(启用分析器) ,这让我想知道这是正确的方式或不。

The strange thing with this (with profiler enabled) is that the memory goes up, which makes me wondering wether this is the correct way or not.

推荐答案

在系统/ core / Loader.php ,Codeigniter执行检查库是否已加载,并且它将不会再次加载。然而,这些检查也消耗一些内存。最后一个方法是最好的加载库,我做了一个小的基准(清除每次尝试后的记忆),这里的结论是:

Around line 914 in system/core/Loader.php, The Codeigniter perform check if the library is loaded and it will not load it again. However, these checks consume some memory as well. To conclude which way is the best for loading libraries, I did a little benchmark (cleaning memory after each attempt) and the conclusion here is:


只需使用 $ this-> load ... 正常加载库,并让Codeigniter处理它

Just load the library normally with $this->load... and let the Codeigniter handle it






基准

$this->load->library('session');

在初始加载Codeigniter会话类之后,我测试了加载库和/或执行检查的各种方式未加载。每一行分别执行20次:

After initial load of Codeigniter session class, I tested various ways loading library and/or performing check if it's not loaded already. Each of these lines were executed separately for 20x times:

记忆消耗测试strong>

MEMORY CONSUMPTION TEST (Not speed!)

if(!$this->load->is_loaded('session')) $this->load->library('session');

这消耗了 48.256字节

if(!class_exists('ci_session')) $this->load->library('session');

这消耗了 39.824字节

if(!isset($this->session)) $this->load->library('session');

这消耗了 31.904bytes

$this->load->library('session');

这消耗了 21.790字节

重复测试一次后,结果是一样的,所以我想它可能是相关的!如果我错了,请评论!

After repeating the test for one more time, the results were the same, so I guess it might just be relevant! Please comment if I'm wrong!

07.08.2014。更新使用Codeigniter 2.2.0:
使用1000次迭代(不像之前的20)重复测试。结果保持不变。内存消耗如下:2128b,1856b,1688b,1456b

07.08.2014. UPDATE using Codeigniter 2.2.0: The test was repeated using 1000 iterations (not 20 like before). The results remain the same. Memory consumption was as follows: 2128b, 1856b, 1688b, 1456b

@Tim Dev在注释中指出,这个基准不需要显示最快的代码,消费代码。

@Tim Dev notes in the comment that this benchmark doesn't necessary shows the fastest code but only lowest memory consumption code.

这篇关于CodeIgniter - 加载库(如果尚未加载)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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