CodeIgniter - Load libraries if not already loaded

拈花ヽ惹草 提交于 2019-12-06 01:05:33

问题


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.

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.


回答1:


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:

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


Benchmark:

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

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:


MEMORY CONSUMPTION TEST (Not speed!)

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

This consumed 48.256 bytes


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

This consumed 39.824bytes


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

This consumed 31.904bytes


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

This consumed 21.790bytes


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. 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 notes in the comment that this benchmark doesn't necessary shows the fastest code but only lowest memory consumption code.



来源:https://stackoverflow.com/questions/19630019/codeigniter-load-libraries-if-not-already-loaded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!