简体   繁体   中英

CodeIgniter - Load libraries if not already loaded

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM