Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PHP - Ds\PriorityQueue::capacity() Function



The PHP Ds\PriorityQueue::capacity() function is used to return the current capacity of the PriorityQueue object. So the capacity is term used to use the maximum number of items that the queue can hold before more RAM needs to be released.

Syntax

Below is the syntax of the PHP Ds\PriorityQueue::capacity() function −

public int Ds\PriorityQueue::capacity( void )

Parameters

This function does not accepts any parameter.

Return Value

This function returns the current capacity.

PHP Version

The capacity() function is available from version 1.0.0 of the Ds extension onwards.

Example 1

First we will show you the basic example of the PHP Ds\PriorityQueue::capacity() function to check the current capacity of the PriorityQueue instance.

<?php
   // Create a new PriorityQueue
   $pq = new \Ds\PriorityQueue();  

   // Check the capacity
   var_dump($pq->capacity()); 
?>

Output

Here is the outcome of the following code −

int(8)

Example 2

In the below PHP code we will shows how the capacity changes or not when we add elements to the queue.

<?php
   // Create a new PriorityQueue
   $queue = new \Ds\PriorityQueue();

   // Initial capacity
   echo "Initial Capacity: ". $queue->capacity(). "\n"; 
   
   $queue->push('Amit', 1);
   $queue->push('Boby', 2);
   $queue->push('Chetan', 3);
   
   // Capacity after adding elements
   echo "Capacity after Adding Elements: ". $queue->capacity();  
?> 

Output

This will generate the below output −

Initial Capacity: 8
Capacity after Adding Elements: 8

Example 3

The example below shows how capacity changes after adding many elements can lead the queue to expand.

<?php
   // Create a new PriorityQueue
   $queue = new \Ds\PriorityQueue();

   for ($i = 0; $i < 100; $i++) {
       $queue->push("Element $i", $i);
   }
   
   // Capacity after adding many elements
   echo "Capacity after adding many elements: ".$queue->capacity(); 
?> 

Output

This will create the below output −

Capacity after adding many elements: 128

Example 4

In the following example, we use the capacity() function to decide if we need to add more elements or stop.

<?php
   // Create a new PriorityQueue
   $queue = new \Ds\PriorityQueue();

   while ($queue->capacity() < 50) {
       $queue->push("New Element", rand(1, 100));
   }
   
   echo "Queue has reached capacity: " . $queue->capacity();
?> 

Output

Following is the output of the above code −

Queue has reached capacity: 64

Summary

These examples show how to use the capacity() function to manage and understand the memory allocation of a Ds\PriorityQueue in PHP.

php_function_reference.htm
Advertisements