Closed. This question is opinion-based。它当前不接受答案。
想改善这个问题吗?更新问题,以便editing this post用事实和引用来回答。
2年前关闭。
Improve this question
我在 C 中具有以下功能:
它分配了内存,然后释放了对象(我将其初始化并复制到创建的列表中),如下所示:
对我来说,使函数内联并按值返回会更好吗?
像这样:
内联会只是通过它而不复制它吗?
想改善这个问题吗?更新问题,以便editing this post用事实和引用来回答。
2年前关闭。
Improve this question
我在 C 中具有以下功能:
GamePiece* init_game_piece(PieceType pieceType, bool isWhite,int column, int row);
它分配了内存,然后释放了对象(我将其初始化并复制到创建的列表中),如下所示:
List* list = board->gamePieces[PIECES_INDEX(isWhite)][piecesArray[i]];
GamePiece* gamePiece = init_game_piece(piecesArray[i], isWhite,i,NON_PAWN_ROW_INDEX(isWhite));
insert_item(list, gamePiece);
board->boardData[gamePiece->gamePieceCell.row][gamePiece->gamePieceCell.column] = get_last_element(list);
free(gamePiece);
对我来说,使函数内联并按值返回会更好吗?
像这样:
GamePiece init_game_piece(PieceType pieceType, bool isWhite,int column, int row);
List* list = board->gamePieces[PIECES_INDEX(isWhite)][piecesArray[i]];
GamePiece gamePiece = init_game_piece(piecesArray[i], isWhite,i,NON_PAWN_ROW_INDEX(isWhite));
insert_item(list, &gamePiece);
board->boardData[gamePiece->gamePieceCell.row][gamePiece->gamePieceCell.column] = get_last_element(list);
内联会只是通过它而不复制它吗?
最佳答案
内联很可能会以您怀疑的方式工作;结构的分配将被消除,如果在启用优化的情况下进行构建,则结构很可能仅在本地声明,因此,即使没有内联函数,您也不会遭受复制损失。
但是,如果您在许多地方使用此函数,并且函数很长,那么缺点将是代码量更大,这比您想象的要糟糕,因为更多的代码意味着更糟糕的缓存行为和性能。现代CPU的使用很大程度上取决于缓存。
但是,所有这些都是推测性的。除非您尝试,否则您确实无法确定,除非您有充分的理由相信程序的这一部分确实会影响性能并且实际上需要优化,否则您就不会真正地尝试。
但是,如果您想尝试一下,则非常有机会尝试尝试,这样很可能会获得更好的性能。
关于c - 我应该按值还是按指针返回struct? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49426639/