E
E
Eugene-1232021-10-28 16:18:46
C++ / C#
Eugene-123, 2021-10-28 16:18:46

Is there a difference, at a low level, between a class with static fields and a global class instance?

Let's say there are two options:
Option 1. Structure with static fields

// MyPool.h
struct MyPool {
  static unsigned int capacity;
  static unsigned int numOfAllocatedObjects;
}

// MyPool.cpp
unsigned int MyPool::capacity {1024};
unsigned int MyPool::numOfAllocatedObjects {0};


Option 2. Global object:
// MyPool.h
struct MyPool {
  unsigned int capacity {1024};
  unsigned int numOfAllocatedObjects {0};
}

extern MyPool MyGlobalPool;

// MyPool.cpp
MyPool MyGlobalPool {};


In the first option, I will not be able to create another instance. But that doesn't interest me. I'm wondering if there is a difference in terms of performance? On another resource, I was told that the second option in terms of codebase support is a bad option.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
Wataru, 2021-10-28
@Eugene-123

No difference.
You can also check it yourself. Technology these days is easy. Here: https://godbolt.org/z/PKWPdY4nn
As you can see, both are compiled into almost the same instructions:

eax, DWORD PTR MyGlobalPool[rip+4]
...
eax, DWORD PTR MyPool1::numOfAllocatedObjects[rip]

And here and there, just loading some static address of a global variable. Generally speaking, in the case of a global variable, the compiler could do 2 things: take the address of the variable and add the offset of the field. But he, as you can see, is smart enough to do everything in one instruction.

U
User700, 2021-10-28
@User700

Most likely there is no low-level difference if we are talking about one glob. object in the second case:
https://godbolt.org/z/YaWccvPx3
It seems to me that if this is a pool for memory allocation, etc., then preferably closer to the second option, because it is possible to create different pools of the same type in one program. Rather, something like shared_ptr on the pool of the allocator is even better ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question