C ++ Static Internal Function

Hello, I have a function that returns std :: pair and is called very often.

std::pair<sf::Vector2i, sf::Vector2i> 
Map::map_coord_to_chunk_coord(int x, int y) {
  // Get the chunk position
  int chunk_x = x / CHUNK_SIZE;
  int chunk_y = y / CHUNK_SIZE;

  // Get the position inside the chunk
  x = x - chunk_x * CHUNK_SIZE;
  y = y - chunk_y * CHUNK_SIZE;

  // Return the chunk position and the position inside it
      return std::pair<sf::Vector2i, sf::Vector2i>(sf::Vector2i(chunk_x, 
chunk_y), sf::Vector2i(x, y));
}

Is it better to declare a pair as static so that it is not created every time.

std::pair<sf::Vector2i, sf::Vector2i> 
Map::map_coord_to_chunk_coord(int x, int y) {
  static std::pair<sf::Vector2i, sf::Vector2i> coords;

  // Get the chunk position
  coords.first.x = x / CHUNK_SIZE;
  coords.first.y = y / CHUNK_SIZE;

  // Get the position inside the chunk
  coords.second.x = x - coords.first.x * CHUNK_SIZE;
  coords.second.y = y - coords.first.y * CHUNK_SIZE;

  // Return the chunk position and the position inside it
  return coords;
}

I run callgrind, and it looks like this function works 3 times faster, but is this good practice?

+4
source share
3 answers

In general, use should be avoided staticwhen the sole purpose is to maintain CPU cycles.

coords static map_coord_to_chunk_coord , , , , .

, std::pair make_pair:

inline std::pair<sf::Vector2i, sf::Vector2i> 
Map::map_coord_to_chunk_coord(int x, int y) {
    int first_x = x / CHUNK_SIZE;
    int first_y = y / CHUNK_SIZE;
    return std::make_pair(
        sf::Vector2i(first_x, first_y)
    ,   sf::Vector2i(x - first_x * CHUNK_SIZE, y - first_y * CHUNK_SIZE)
    );
}

, .

+6

, , , , .

, ++ . ( ), std::pair of sf::Vector2i , , , :

void
map_coord_to_chunk_coord(int x, int y, std::pair<Vector2i, Vector2i>& chunk_coord) {
    chunk_coord.first.x = x / CHUNK_SIZE;
    chunk_coord.first.y = y / CHUNK_SIZE;
    chunk_coord.second.x = x % CHUNK_SIZE;
    chunk_coord.second.y = y % CHUNK_SIZE;
}

chunk_coord , std::pair sf::Vector2i.

+2

.

( !), .

( .)

, , , .

+1

Source: https://habr.com/ru/post/1677164/


All Articles