Lazy loading in PHP

In more pro­jects than I care to think about, I’ve seen a pat­tern that I dis­li­ke the more I see it. It appears quite inno­cent, but it brings about cost with no dis­cer­ni­ble benefit. 

Inclu­ding all of the application’s source code on each and every call being made to a page. It may be that one file is included that lists all files the app brings along; it may be a list of require_once state­ments in every ent­ry page it has. But what is the bene­fit? Even if the page loads only tho­se files that it might even­tual­ly need, it pro­ba­b­ly includes more than is war­ran­ted given the task it is curr­ent­ly given.

One solu­ti­on is to get into using an auto­loa­der; let the inter­pre­ter figu­re out by its­elf whe­ther it has alre­a­dy seen all that it needs to exe­cu­te a given pie­ce of code. The other opti­on is to requi­re exter­nal files only at the point that you’­re cer­tain that you need them. Does your code do input sani­tiz­ing and vali­da­ti­on befo­re it loads the clas­ses that then work with the sani­ti­zed values? Pro­ba­b­ly not – it’s much more com­mon to first load all the code, and only then start to work with what you are given. 

Lazy loa­ding means that the inter­pre­ter only runs on tho­se code parts it needs, hel­ping to con­tri­bu­te to bet­ter appli­ca­ti­on per­for­mance (becau­se we’­re not spen­ding time on code we don’t real­ly need, any­way). This also means using less resour­ces on the ser­ver, which means bet­ter use of resour­ces – ulti­m­ate­ly, having your code use less elec­tric power. But the­re is even more bene­fits: code that has not been loa­ded can­not be caus­ing any kind of inter­fe­rence; you’­re cer­tain that you don’t have to look into tho­se files when you’­re debug­ging. And then, code that has not been loa­ded also can­not be used for secu­ri­ty exploits–so you have less side effects the­re as well. 

It’s not that this is a par­ti­cu­lar­ly com­plex intellec­tu­al chall­enge, it’s more a mat­ter of per­spec­ti­ve and may­be wri­ting infra­struc­tu­re code for your app. But to me, the bene­fits are worth the few more minu­tes spent whilst thin­king about your code.


Beitrag veröffentlicht

in

,

von

Schlagwörter:

Kommentare

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert