Lazy_static! vs const vs let

FILTERS: String = json!({
            "filters": {
                "price": 0,
                "status": "all",
                "listingsStatus": "",
                "page": 1,
                "from": 0,
                "discountedItems": 1,
                "overpricedItems": 0,
                "search": "",
                "perPage": 50,
                "userId": ""
            "selectedBalance": "bux"

Lets say i have a json body like this and will use it over and over again by post requests (every 1 second) which one should i use?

Creating const variable, putting it into lazy_static or creating with let local variable when related function triggers (related fn will be called for every 1 second).

Would be good also if i can have detailed explanation.

Note: Reason of this is im making post request in a loop and that value will be used over and over again so trying to make the loop fast as possible as i can.

If it's a constant json like that, I would just get the serialized value and store it in a string literal.

let filters: &str = r#"{"filters":{"discountedItems":1,"from":0,"listingsStatus":"","overpricedItems":0,"page":1,"perPage":50,"price":0,"search":"","status":"all","userId":""},"selectedBalance":"bux"}"#;

that way you don't need to do any processing at runtime.

If you need to parameterize it then const/static doesn't make any sense, you have to use let.

1 Like

Hmm in the definition i saw that lazy_static! are initialized only once, are shared among all threads, and can be directly acces. And u are suggesting to use borrowing the string literal.
Where to use lazy_static then ?

You would use lazy_static, or alternatively once_cell, in cases where you cannot use a string literal.

For example, imagine that part of the JSON string came from a command line argument, or a configuration file. Then you would have to do a heap allocation, but you would rather only do that once.


To add to this, you could also have it in a file, and use

const FILTERS: &str = include_str!("the_filters.json");

so that you don't have to have the one super-line line in your code, and you can get nice json highlighting in the file.

(That builds it into your binary, so you don't need to distribute the file, as opposed to what would happen if you load it at runtime.)

Wouldunt const be slow ? cuz its inlined and u are copy pasting the value over and over again ?

There's a chance you'd get multiple copies in your binary, but they'd probably be promoted to static memory and not on the stack or anything. It might slow compilation slightly if that's what you meant. Using static instead of const would address either concern.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.