When one decides to use lazy initialization, he usually has to pay for it.
class Loafer
{
private VeryExpensiveField field;
private VeryExpensiveField LazyInitField()
{
field = new VeryExpensiveField();
// I wanna here remove null check from accessor, but how?
return field;
}
property Field { get { return field ?? LazyInitField(); } }
}
Basically, he has to check every time if his backing field has null/nil value. What if he could escape from this practice? When you successfully initialize the field, you can rid of this check, right?
Unfortunately, majority of production languages do not allow you to modify their functions in run-time, especially add or remove single instructions from the function body though it would be helpful if used wisely. However, in C#, you can use delegates (initially I discovered them and afterwards realized why native languages having function pointers for) and events mechanism to imitate such behavior with consequent lack of performance, because null-checks just move onto lower level, but do not disappear completely. Some languages, e.g. LISP and Prolog, allow you to modify their code easily, but they are hardly can be treated as production languages.
In native languages like Delphi and C/C++ it seems better to write two functions, safe and rapid, call them by pointer and switch this pointer to rapid version after initialization. You can even allow compiler or IDE to generate code to do this without additional headache. But as @hvd mentioned, this can even decrease speed, because CPU will not know that those functions are almost the same, thus will not prefetch them into it's cache.
Yes, I'm performance maniac seeking for performance without explicit problem, just to feed my curiosity. What common approaches are exist to develop such functionality?