Skip to content
← All posts
· Delta1 Labs ObfuscationNebula

The runtime cost of string encryption in a hot loop

Encrypted string literals are decrypted at the point of use. In a tight loop that adds up. Here is how to measure the cost with BenchmarkDotNet and scope string encryption in nebula.config.json.

String encryption is one of the cheapest, highest-value transforms Nebula.NET applies: it turns every readable literal in your assembly — API endpoints, format strings, license messages, the names of things — into an encoded blob that is decoded only at runtime. Open the protected binary in a decompiler and the roadmap those literals used to draw is gone. For the overwhelming majority of code, it is free in every sense that matters.

The one place it is not free is a hot loop. An encrypted literal is decrypted at the point of use, and “the point of use” can be inside a method that runs millions of times. A decode that costs a few nanoseconds is invisible once; multiplied across a tight inner loop it becomes something you can measure. This post is the how-to: what “decrypted at use” actually compiles to, how to measure the cost honestly with BenchmarkDotNet, how decode caching changes the picture, and how to scope string encryption in nebula.config.json so you protect the valuable strings without taxing the hot ones.

What “decrypted at use” compiles to

Before protection, a literal is a single IL instruction. This method:

public bool IsAdmin(string role) => role == "administrator";

compiles the literal to one ldstr, which the runtime resolves to an interned string with zero work:

ldarg.1
ldstr      "administrator"
call       bool [System.Runtime]System.String::op_Equality(string, string)
ret

After string encryption, Nebula replaces the ldstr with a call to a generated decode routine that takes an opaque token and returns the plaintext. Conceptually the IL becomes:

ldarg.1
ldc.i4     0x1F3A           // token / offset into the encrypted blob
call       string Nebula.Runtime.Strings::Get(int32)
call       bool [System.Runtime]System.String::op_Equality(string, string)
ret

The literal is no longer in the metadata as text; it lives in an encrypted table, and Strings::Get decodes the entry for that token when the line executes. That decode is the entire runtime cost of string encryption — and the entire question of whether you will ever notice it is how often that call runs.

Where the compiler already saved you

Here is the detail that makes string encryption cheap in practice: most literals are not decoded on every use, because the C# compiler hoists them before Nebula ever sees them. A literal referenced in a method body is frequently lifted to a static field initialised once. When that happens, the decode runs a single time on first access and every later use reads the field.

So the loop you are afraid of often does not have the cost you fear:

// The literal is effectively hoisted; it is decoded once, not per iteration.
for (int i = 0; i < items.Length; i++)
    if (items[i].Kind == "invoice")   // "invoice" resolves from a one-time decode
        Process(items[i]);

The cost becomes real in the opposite shape — where a distinct literal is constructed or selected inside the loop body on the hot path, especially when it feeds string formatting or building that already dominates the loop:

// Hot path: runs per row, millions of times. Each distinct literal is a decode.
foreach (var row in rows)
    log.Trace($"row {row.Id} status={row.Status} at {"yyyy-MM-ddTHH:mm:ss"}");

The honest answer to “which shape is my hot path?” is not something you can read off the source. You measure it.

Measuring it with BenchmarkDotNet

Do not reason about nanoseconds from a decompiler; benchmark the real method before and after protection. The pattern is to build the method both ways and run the same workload through each. A minimal sketch:

[MemoryDiagnoser]
public class HotPathBench
{
    private readonly Record[] _rows = Record.Generate(1_000_000);

    [Benchmark(Baseline = true)]
    public long Plain() => Sum(_rows);      // unprotected build

    [Benchmark]
    public long Protected() => SumProtected(_rows);   // same code, string-encrypted

    private static long Sum(Record[] rows)
    {
        long n = 0;
        foreach (var r in rows)
            if (r.Status == "active") n++;   // literal on the hot path
        return n;
    }
}

Run it against a build produced by nebula protect and read the delta, not the absolute numbers:

nebula protect --config nebula.config.json --out bin/Protected

A representative result on a loop whose literal is hoisted looks like noise — the decode happened once, off the measured path:

| Method    | Mean      | Ratio | Allocated |
|---------- |----------:|------:|----------:|
| Plain     |  2.41 ms  |  1.00 |       0 B |
| Protected |  2.43 ms  |  1.01 |       0 B |

A loop that decodes a distinct literal per iteration tells a different story, and that is exactly the method you want to find and scope:

| Method    | Mean      | Ratio | Allocated |
|---------- |----------:|------:|----------:|
| Plain     |  2.41 ms  |  1.00 |       0 B |
| Protected |  9.80 ms  |  4.07 |  48,000 B |

The ratio column is the whole decision. A ratio of 1.01 means leave it encrypted — the protection is free here. A ratio of 4.07 on a method that dominates your runtime means scope it out. You are not choosing between “protected” and “fast” for the whole assembly; you are choosing it per hot path, with a number.

String decode cost: hoisted vs inline vs scoped-out hot loopRelative runtime of a 1M-iteration hot loop0×1×2×4×hoisted1.01×inline, hot4.07×scoped out1.00×per-iteration decodeencryptedexcluded from encryption

How caching changes the picture

Nebula.NET does not decode blindly on every call. Where a decoded string’s reference is stable, the runtime caches the plaintext after first decode and serves it from the cache thereafter, so a literal that resolves to the same value amortises its cost no matter how often the line runs. This is why the hoisted-literal case benchmarks as noise and why most encrypted strings never show up in a profile.

The cache helps exactly where the literal is stable and helps nothing where a distinct value is produced each iteration — a per-row interpolated format, a composed key, a message built from parts. That is the shape to hunt for: not “a literal in a loop,” but “a different decoded value per iteration on a path that already dominates runtime.” Everything else, leave encrypted and forget about.

Scoping string encryption in nebula.config.json

Once a benchmark has named a hot method, exclude that scope from string encryption and leave the rest of the assembly protected. Nebula.NET takes include/exclude patterns under stringEncryption, evaluated so that an explicit exclude wins. Scope by namespace or type when the hot code lives together:

{
  "schemaVersion": 1,
  "inputs": [ "bin/Release/net8.0/Acme.Pricing.dll" ],
  "outputDirectory": "protected",

  "stringEncryption": {
    "enabled": true,
    "exclude": [
      "Acme.Pricing.Engine.Hot.*",
      "Acme.Pricing.Serialization.RowFormatter"
    ]
  },

  "controlFlow": { "enabled": true }
}

Everything in Acme.Pricing.* keeps its strings encrypted except the measured hot namespace and the one formatter the benchmark flagged. When the hot path is a single method rather than a whole namespace, mark it in code and exclude by attribute — the rule then lives next to the method it describes and survives refactors:

[Obfuscation(Feature = "stringEncryption", Exclude = true)]   // benchmarked: 4.07× per-row decode
public void FormatRows(ReadOnlySpan<Record> rows, TextWriter w) { /* ... */ }
"stringEncryption": {
  "enabled": true,
  "exclude": [ "hasAttribute:System.Reflection.ObfuscationAttribute" ]
}

If instead you want the inverse posture — encrypt only the strings that are genuinely sensitive and leave everything else as plain literals — flip to an include and name the valuable scopes:

"stringEncryption": {
  "enabled": true,
  "include": [ "Acme.Pricing.Licensing.*", "Acme.Pricing.Security.*" ]
}

That is the right posture when a profile shows a lot of string-heavy hot code and only a small, well-contained set of secrets. Most projects do the opposite — encrypt broadly, exclude the one or two measured hot paths — because the default of “protect everything” is the safe one and the exclusions are rare.

A rule of thumb

Separate valuable strings from hot strings, because they are almost never the same strings. Your secrets — endpoints, key material, license-check messages, the names of your proprietary types — live in setup code, auth paths and licensing logic that run occasionally. Your hot strings — a status compared per row, a format applied per request — live in loops and carry no secret at all. String encryption earns its keep on the first set and taxes you only on the second.

So the workflow is: encrypt strings across the whole assembly by default, profile or benchmark the two or three methods that dominate your runtime, and if one of them shows a real decode cost in BenchmarkDotNet, exclude that scope and nothing more. You end up with every secret encrypted, a decompiler that reveals nothing useful, and a hot path that runs at plain-literal speed — which is the entire point of scoping rather than toggling. Pair it with control-flow obfuscation on the licensing methods those strings live in, and verify the protected result in Glass.NET before you ship.

See Nebula.NET for the full transform set and the nebula.config.json reference.

Try Nebula.NET

Harden your .NET code in minutes — start with the free edition.