PHP - Ds\PriorityQueue::allocate() Function
The PHP Ds\PriorityQueue::allocate() function is available in the Ds (Data Structures) extension for PHP which is used to allocate a specific capacity to a priority queue. This can improve performance by reducing the need to resize when objects are added.
Syntax
Below is the syntax of the PHP Ds\PriorityQueue::allocate() function −
public Ds\PriorityQueue::allocate(int $capacity): void
Parameters
This function accepts $capacity parameter which is an integral value that indicates how many values needs capacity to be allotted.
Return Value
This function does not return a value.
PHP Version
The allocate() function is available from version 1.0.0 of the Ds extension onwards.
Example 1
Here is the basic example of the PHP Ds\PriorityQueue::allocate() function to allocate a capacity of 10 to a priority queue.
<?php // Create a new PriorityQueue $queue = new \Ds\PriorityQueue(); //Use allocate function here $queue->allocate(10); //echo the message echo "Capacity allocated: 10\n"; ?>
Output
Here is the outcome of the following code −
Capacity allocated: 10
Example 2
In the below PHP code we will try to use the allocate() function and we start adding elements to the queue after allocating space for five items.
<?php
// Create a new PriorityQueue
$queue = new \Ds\PriorityQueue();
// Use allocate function here
$queue->allocate(5);
$queue->push("A", 1);
$queue->push("B", 2);
$queue->push("C", 3);
echo "The elements are:\n";
foreach ($queue as $value) {
echo $value . "\n";
}
?>
Output
This will generate the below output −
The elements are: C B A
Example 3
Now the below code, we will check the capacity before and after allocation using allocate() function.
<?php // Create a new PriorityQueue $queue = new \Ds\PriorityQueue(); echo "Initial capacity: " . $queue->capacity() . "\n"; $queue->allocate(20); echo "Capacity after allocation: " . $queue->capacity() . "\n"; ?>
Output
This will create the below output −
Initial capacity: 8 Capacity after allocation: 32
Example 4
In this example, a capacity is allocated initially using allocate() function, and additional elements are added until the capacity is exceeded.
<?php
// Create a new PriorityQueue
$queue = new \Ds\PriorityQueue();
$queue->allocate(2);
$queue->push("X", 1);
$queue->push("Y", 2);
$queue->push("Z", 3); // Exceeds initial allocation
echo "After exceeding the initial allocation: \n";
foreach ($queue as $value) {
echo $value . "\n";
}
?>
Output
Following is the output of the above code −
After exceeding the initial allocation: Z Y X
Summary
The Ds\PriorityQueue allocate() function can ensure that enough memory is allocated for the required capacity. It can remove the need to reallocate internal as values are added.