关于 c++ 中 std::cout 的效率以及打印消息的替代方法

发布于 2025-01-11 23:28:42 字数 977 浏览 4 评论 0原文

我正在学习 C++,作为练习,我正在实现一个粗略的 ASCII 渲染器,我的渲染函数看起来像这样:

void render() {
    for(int y = 0;y < height;y++) {
        for(int x = 0;x < width;x++) {
            std::cout << getCharOfPixel(x, y);
        }
        std::cout << '\n';
    }
}

但我想知道将整个内容存储在字符串中并打印出整个内容是否会更有效一次字符串,如下所示:

void render() {
    std::string finalString((width + 1) * height, '\0'); // initializing the string with ((width + 1) * height) null characters, to avoid resizing efficiency lack
    int characterIndex = 0; // where we are writing to finalString
    for(int y = 0;y < height;y++) {
        for(int x = 0;x < width;x++) {
            finalString[characterIndex++] = getCharOfPixel(x, y);
        }
        finalString[characterIndex++] = '\n';
    }
    std::cout << finalString;
}

更具体地说,我问 std::cout 的效率是否取决于我正在写入的字符数或调用它的次数

I'm learning C++, and as a exercise i am implementing a crude ASCII renderer, and my render function looks something like this:

void render() {
    for(int y = 0;y < height;y++) {
        for(int x = 0;x < width;x++) {
            std::cout << getCharOfPixel(x, y);
        }
        std::cout << '\n';
    }
}

but i wonder if it could be more efficient to store the whole thing in a string and just print out the whole string at once, like this:

void render() {
    std::string finalString((width + 1) * height, '\0'); // initializing the string with ((width + 1) * height) null characters, to avoid resizing efficiency lack
    int characterIndex = 0; // where we are writing to finalString
    for(int y = 0;y < height;y++) {
        for(int x = 0;x < width;x++) {
            finalString[characterIndex++] = getCharOfPixel(x, y);
        }
        finalString[characterIndex++] = '\n';
    }
    std::cout << finalString;
}

more specifically, I'm asking if the efficiency of std::cout depends on how many characters i am writing or how many times i invoke it

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文