Answer the question
In order to leave comments, you need to log in
Which is faster - global variable or class initialization in another class?
Good afternoon everyone!
I am currently working on a project that will work under high load. Now I asked myself the following question:
For example, there is a class for working with a database:
class Database
{
/* что-то тут делаем */
}
$db = new Database()
global $db;
class User
{
public $database;
public function __construct()
{
$this->database = new Database();
}
public function something()
{
$this->database->query();
}
}
Answer the question
In order to leave comments, you need to log in
First, it is economy on matches. Opcacher will actually remove the difference between the approaches.
Second, a global variable will be faster.
Thirdly, why write a separate class for working with the database? There are a maximum of two functions - connecting to the database and executing a request.
> I am currently working on a project that will work under high load.
> What is faster - a global variable or class initialization in another class?
I'm afraid you don't even know what "high loads" are. By the way, did you think about replacing double quotes with single quotes and shortening variable names to 4 letters (so that they fit into 1 processor register)?
It will work about equally fast. Much more important is "which is more convenient." You can also use a ready-made framework for the model if you are interested in the result and the deadline, and not learning to design in practice. To support high loads, in my opinion, it is more important to pay attention to the architecture of the cluster, in which you can quickly add new nodes. And to optimize the code later, enjoying the monitoring reports, to save server costs.
And I would probably store everything I need in a global class, and during initialization I would simply pass a pointer to this very global class ... I don’t know how correct this is.
Offtopic: I would do this, if I already knead the database with entities a la ActiveRecord
class Entity
{
protected $database;
public function __construct(Database $database)
{
$this->database = $database;
}
}
class User extends Entity
{
public function __construct(Database $database)
{
parent::__construct($database); // дурная привычка, чтобы не забыть если решу конструктор расширить
}
public function something()
{
$this->database->query();
}
}
$user = new User(Database::getInstance());
Use singleton. Moreover, parameterized to be able to open more than one connection to the database - at least for reading and writing. And with the implementation of "lazy loading"
If you do not understand why the separation of connections is needed, it does not matter to you and there is a big difference in performance by several orders of magnitude. If you understand, then why this question?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question