r/C_Programming • • 4d ago

Question Design choice with enums and strings

I'm working on a C minecraft clone, and I've been refactoring a bunch of my block code. Previously a "block" was just an enum, I essentially "hardcoded" the list of blocks in the game itself. Part of the refactor is using a JSON file for defining blocks and their metadata. However, because of this, I've now reached a weird place. The JSON defines the ID as a string. The enum that was BLOCK_GRASS is now a string in the JSON as "BLOCK_GRASS".

The design question I have is should I be referencing a string in my code, and doing comparisons with strings? Or do I need to have some sort of intermediate mapping of string IDs -> enum IDs. The latter seems kind of wasteful since it just means all the benefits of the JSON config file went away.

Not sure what the general consensus is. The strings are going to be in the data section anyways so I don't think I'm being wasteful with allocations here.

8 Upvotes

33 comments sorted by

15

u/catbrane 3d ago

I'd keep strings in the JSON and map them to and from enum values on load and save. The point of the JSON file is to isolate save files from C enum values, so it's still worthwhile.

You could use pointers to static strings and just pointer compare, since your C compiler will common up all strings like "BLOCK_GRASS", but it would be so easy to make a small mistake and have a very tricky bug. Ints are safer and easier to debug.

4

u/space_junk_galaxy 3d ago

Fair enough. I guess I only really need to map the IDs, the rest of the data isn't needed at compile time so it should work. Thanks!

1

u/space_junk_galaxy 3d ago

Reading this back and I want to clarify - this isn't about save files, it's about block metadata (a grass block being solid, for example). What I've read is that MC uses a registry like system, but I don't understand what the purpose of the string-based keys are in that system, since you would only ever refer to them via the well-defined typed variables.

7

u/tstanisl 4d ago

The main problem is that comparison of strings requires indirection and looping and difficult to predict branching. All of those are very slow on modern CPUs. Comparing tiny `int` can often be allow to eliminate branching by using masking technique. So if you care about performance, use integer identifiers.

In some cases, string comparison can be replaced with comparison of pointers but you must first make sure that all potentially compared strings comes from the same pool with no duplicates.

-1

u/Wertbon1789 3d ago

Comparing pointers doesn't really makes sense when talking about comparing strings, as you usually compare against static strings, that are in .rodata, and your JSON would most likely be on the heap, so they'll never match.

It's also not that bad to compare strings. Especially modern CPUs don't struggle with it that much, older ones did more so. It's not ideal, but also not a death sentence, not even close. Most of Linux's ABI for example is strings, some part of that is probably because it's unambiguous in endianess, and the ability to consume everything with a shell, but it's just a fact at that point, and it's not that big of a concern.

4

u/tstanisl 3d ago edited 3d ago

Comparing pointers doesn't really makes sense

Yes. Replacing strcmp with == requires a lot of impractical assumptions. Though they may satisfied for virtual machines where all string's management is globally controlled.

It's also not that bad to compare strings.

Yes, CPUs have dedicated instructions for that operation. If a small pool of strings is placed in L1 cache, and strings have no common prefix then the strcmp can be relatively fast. But the simple comparison of enums will likely be a lot faster than that optimistic scenario.

6

u/aeropl3b 3d ago

I am not entirely sure your problem. JSON is a serialization format, not a C representation.

If the idea is you are going to permit dynamic block types via JSON config, then I would use a registery of block types, and a handle to the block meta data. The handle can just be an int that points to an offset in an array of block data.

A block instance could then be a handle, coordinate data, durability, etc. Effectively the same as the current enum approach, but the enums are now dynamicly assigned ints.

4

u/Agitated_Ad_5989 4d ago

Save them as the integer the enum value is representing

1

u/RussianHacker1011101 3d ago

This doesn't directly answer your question, but I'd like to make a suggestion. Use SQLite rather than a JSON file. You'll inevetably want need to modify this file. It could grow to be very large. You also might want a serialization format for "saved game" or for a level builder. You can also easily pivot between string ids and integer ids. And you could import your JSON file directly into SQLite and query it (in order to import it into a table).

1

u/space_junk_galaxy 3d ago

Sorry post wasn’t clear - this isn’t for game saves, it’s for loading block config data at runtime. Like block properties and stuff 

2

u/Rabbitical 3d ago

Your JSON storage method and your internal program operation need not and should not be the same at all. The point of JSON is to be human readable, the point of your enums is to bridge the gap between human readable and integers which make the computer happy. Once you load your blocks from JSON, you use string comparisons to assign enum values and then never deal in strings again.

2

u/GoblinsGym 3d ago

One trick that you can use is limit string names to 4 or 8 characters, then you can do a quick integer compare.

For internal stuff I use a textual format like this:

name value

Names are 4 character codes, cast to a 32 bit integer and have a big switch statement...

2

u/Maxwelldoggums 3d ago

You could use a hash of the string at runtime to convert it to an arbitrary integer.

1

u/Jonatan83 3d ago

It's hard to answer without knowing how you are using it. How often will you be comparing? Maybe you can compare hashes instead (and assume or verify that there are no collisions).

1

u/8d8n4mbo28026ulk 3d ago edited 3d ago

Intern your strings and you can just compare them by their identity. If your code compares IDs, you'd want to intern them anyway, since the config file might contain bogus values.

1

u/RealisticDuck1957 3d ago

If the intent is to get away from hard coded block types (a good idea), the data file defining types should have a number ID associated with each type. A string may also be defined for human interface.

1

u/Gold-Part4688 3d ago

if the strings stay statically in memory throughout, and are only defined once - can you just compare their pointers?

1

u/Traveling-Techie 3d ago

Think about generating your code with a program using configuration files.

1

u/wsppan 2d ago

The point of Json is to have a format you can serialize data structures in your code in order to pass around to different services via REST API calls.or, in your case, between your code and the file system. You should not conform your codes data structures to what is used in the serialized Json. Create serialize/desensitize libraries and use them.

0

u/tastygames_official 3d ago

ooh, don't use JSON. It's not very performant: https://nee.lv/2021/02/28/How-I-cut-GTA-Online-loading-times-by-70/

Just save it as an integer and use a custom file format instead of JSON. You can use an 8-but unsigned int and have 255 block types, then your file format might have something like

byte 1: block type
2-5: float x pos
6-9: float y pos
10-13: float z pos
14: uint8_t how many characters are in the next string
15-?: string of characters for the name or whatever

then just use a series of fread()s to read all the data.

Now if you don't have that many block types, you can even use a nibble or even just a few bits for the block type and then use the other bits for other flags so you can still hit that 8-bit alignment.

2

u/-moron 3d ago

For storing chunks, yes, but I think OP is talking about fixed block names and behaviours like hardness, which need to be easy to change with a text editor.

1

u/space_junk_galaxy 3d ago

Yeah pretty much that. A grass block being solid and opaque etc.

1

u/tastygames_official 3d ago

if it's a requirement that it needs to be editable in a text editor, then yes: JSON is my favourite human-readable format. Although I think YAML is a bit more performant. XML is the worst. But even then, a coverter to a binary format would be quite important I think for a minecraft clone where I imagine millions of blocks in a world.

So if it were me and I needed a JSON file so users can edit levels in text then I'd create a tool for them to convert it to a more compact format for the game engine to read in. Then you can keep the JSOn format as human-readable as possible (e.g. "block_type": "grass") but then for optimal performance that would translate to something like I stated above.

And another obvious solution is a custom editor where the user can select "grass" from a drop-down or whatever and it will save the file in a compact format.

thoughts, u/space_junk_galaxy ?

1

u/space_junk_galaxy 3d ago

I'm not sure performance is at play here, because this config file is read once during startup and that's it.

1

u/tastygames_official 3d ago

but if it's millions of block data all read sequentially then you could be talking minutes vs. seconds of loading time.

1

u/space_junk_galaxy 3d ago

I think I've phrased this question badly, since a lot of people are getting confused. This is not for world save data.

This is a config file defining block metadata - for example, a grass block is opaque + solid, while a water block is neither.

1

u/tastygames_official 3d ago

right - but your world will likely have millions of blocks, correct? So whether saving and loading to/from disk or keeping all that information in memory, you're going to want it to be as compact as possible. That means combinind multiple flags into a single byte (or however many flags you have) and using bitwise operations to get at the individual flags. It means storing things like block type as a byte (if you have fewer than 255 types, otherwise you need 2 bytes), etc. If you also need human-readable format like JSON or YAML, you can do that too, but only for import/export and not during the actual game. But as I said, even then, if you're loading or saving millions of blocks then staying away from human-readable is a big performance boost.

But if it's only for a few hundred blocks, then I guess maybe it really doesn't matter on modern systems.

1

u/space_junk_galaxy 3d ago

Yes, my world does have millions of blocks, and the in-memory representation of those blocks is a simple enum, which is the block ID. The config file is only a few 100 bytes, and that is stored once. ID maps to values in config file, so I'm not duplicating anything. And yeah I already have some flags as bits, but I've never really had any performance issues.

1

u/SuspiciousScript 3d ago

The actual problem in the article you linked is with the implementation using a badly hand-rolled parser, not JSON itself.

1

u/Maxwelldoggums 3d ago

It’s not that JSON isn’t performant, in the example you give their json parser is just poorly written.

Yes JSON will never be as fast as binary serialization, but you can parse JSON easily in a single pass with no backtracking or allocation. For any personal project, a well written JSON parser will be fine.

0

u/-moron 3d ago edited 3d ago

Scrap the global enum to save compile time when modifying or adding block types. You could use YAML or something so you can store the block ID keys as integers instead of strings. Or just store the blocks in a list in the JSON file and use the index. It's best to work with integers over strings when possible.

0

u/LaggerFromRussia 3d ago

If you configuring the blocks in json, why do you need enum IDs in the code? What you want is probably a hashmap of string->block. For saving the world you can do the same trick as minecraft: each chunk contains palette - array of block states (including string ID), chunk saves blocks as indexes in it's palette. (Actually, it's a little trickier: chunk->sections->block_list+block_states->data+palette.)